title: Export JPG out of Dicom File With mDCM
body: <p>I'm using mDCM with C# to view dicom tags, but I'm trying to convert the pixel data to a Bitmap and eventually out to a JPG file. I have read all of the posts on the mDCM Google Group on the subject and all of the code examples either don't work or are missing important lines of code. The image I am working with is a 16 bit monochrome1 (that's the format mentioned, but it's actually 16 bit grayscale). I have tried using LockBits, SetPixel, and unsafe code in order to convert the pixel data to a Bitmap but all attempts fail. Does anyone have any code that could make this work.</p>
  
  <p>Here is my latest attempt using SetPixel:</p>
  
  <pre><code>DcmElement pixelData = this.currentFileFormat.Dataset.GetElement(new DcmTag(DcmConstTags.PixelData));
  ushort[] pixels = this.currentPixelData.GetFrameDataU16(0);
  this.currentImage = new Bitmap(this.currentPixelData.ImageWidth, this.currentPixelData.ImageHeight, PixelFormat.Format16bppRgb555);
  int resample = (int)Math.Pow(2, (this.currentPixelData.BitsStored - 8));
  
  int pxCounter = 0;
  int min = ushort.MaxValue;
  int max = 0;
  
  for (int c = 0; c &lt; this.currentPixelData.ImageHeight; c++)
  {
      for (int r = 0; r &lt; this.currentPixelData.ImageWidth; r++)
      {
          ushort pxColor = pixels[pxCounter];
          int temp = 255 - (pxColor / resample);
          if (temp &lt; min) min = temp;
          if (temp &gt; max) max = temp;
          this.currentImage.SetPixel(r, c, Color.FromArgb(temp, temp, temp));
          pxCounter++;
      }
  }
  </code></pre>
  
  <p>UPDATE:
  I have gotten closer by using LockBits and Marshal.Copy, but the image comes out in a rainbow of colors instead of grayscale. So I'm guessing I need a way to convert the grayscale data to RBG format:</p>
  
  <pre><code>byte[] pixels = this.currentPixelData.GetFrameDataU8(frameIndex);
  this.currentImage = new Bitmap(this.currentPixelData.ImageWidth, this.currentPixelData.ImageHeight, PixelFormat.Format16bppRgb555);
  BitmapData bitmapData = this.currentImage.LockBits(new Rectangle(0, 0, this.currentImage.Width, this.currentImage.Height), ImageLockMode.ReadWrite, this.currentImage.PixelFormat);
  System.Runtime.InteropServices.Marshal.Copy(pixels, 0, bitmapData.Scan0, this.currentImage.Width * this.currentImage.Height * 2);
  this.currentImage.UnlockBits(bitmapData);
  </code></pre>
  
  <p>Thanks in advance</p>
  
  <p>P.S. Before anyone suggests trying something else like ClearCanvas, know that mDCM is the only library that suits my needs and ClearCanvas is WAY too bloated for what I need to do.</p>