1

I'm using DICOM#(http://sourceforge.net/projects/dicom-cs/) to convert a dicom file (.dcm) to a .jpg. The code i've done:

string strFileName = nomeFile;
string strOutFileName = Server.MapPath("uploads/" + "teste");
Stream ins = null;
Dataset ds = null;
FileStream fs = new FileStream(strFileName, FileMode.Open, FileAccess.Read);
System.IO.Stream strm = fs;

Dataset imgds;
imgds = new Dataset();
imgds.ReadFile(strm, FileFormat.DICOM_FILE, 10000);

ByteBuffer byteBuffer = imgds.GetByteBuffer(Tags.PixelData);
byte[] byteArray = (byte[])byteBuffer.ToArray();

MemoryStream ms = new MemoryStream(byteArray);
Image returnImage = Image.FromStream(ms);
strOutFileName = strOutFileName + ".PNG";
returnImage.Save(strOutFileName, ImageFormat.Png);

But this give me an error:

An exception of type 'System.ArgumentException' occurred in System.Drawing.dll but was not handled in user code

In this line:

Image returnImage = Image.FromStream(ms);

Does anyone have a solution?

martinez314
  • 12,162
  • 5
  • 36
  • 63
stack01
  • 21
  • 3

1 Answers1

0

It looks like the problem is in decoding the image from the stream. An ArgumentException is unfortunately a very generic error that System.Drawing classes throw when the underlying GDI library can't deal with what you give it. I'd suspect one of:

  1. You don't have all the bytes in the array that you create from ByteBuffer so Image.FromStream can't decode it

  2. The data from ByteBuffer is too large for GDI to make an image from

  3. The data is not a known image format, and Image.FromStream can't decode it. (e.g. is it Raw pixel data? If so, you have to build the image differently, by writing the pixel bytes to the encoder)

Extra tip:

Using 10000 for the buffer size passed to ReadFile is not optimal. Blocks read from the underlying filesystem are a multiple of 4096 bytes, and a best-fit buffer will have the same multiple. See: Optimum file buffer read size?.

Community
  • 1
  • 1
codekaizen
  • 26,990
  • 7
  • 84
  • 140
  • See the other Dicom image pixel module attributes (Dicom C.7-11 http://dicomlookup.com/lookup.asp?sw=Ttable&q=C.7-11 ) in the dicom file you're trying to read for the actual stored format. – Kasper van den Berg May 23 '15 at 19:41
  • Sounds like a good practice, but `Image.FromStream` should decode it if it is a well known (i.e. supported by GDI) encoding. – codekaizen May 23 '15 at 19:54
  • DICOM appears to use raw pixel data, or did I misintrepret table C.7-11? – Kasper van den Berg May 23 '15 at 20:01
  • @codekaizen It can work but windows does not ship with a DICOM handler for GDI. It will only work if you install a handler for it (I don't know if DICOM# does that or not) – Scott Chamberlain May 23 '15 at 23:08