0

I want to convert a 12bit gray image into an 8 bit representation, to be able to display it correctly. Here is how:

 byte[] dstData = null;
  BitmapImage displayableBitmapImage = null;

  if (numberOfBitsUsed == 12 || numberOfBitsUsed == 16)
  {
    int height = image.PixelHeight;
    int width = image.PixelWidth;
    int bytesPerPixel= ((image.Format.BitsPerPixel + 7) / 8);
    int stride = width * bytesPerPixel;

    // get the byte array from the src image
    byte[] srcData = new byte[height * stride];
    image.CopyPixels(srcData, stride, 0);

    // create the target byte array
    dstData = new byte[height * width]; 


    for (int j = 0; j < height; j++)
    {
      for (int i = 0; i < width; i++)
      {
        int ndx = (j * stride) + (i * bytesPerPixel);
        //get the values from the src buffer
        byte val1 = srcData[ndx + 1];


        //convert the value to 8bit representation
        if (numberOfBitsUsed == 12)
        {
          byte val2 = srcData[ndx];
          //the combined value of 2 bytes
          ushort val = (ushort)((val1 << 8) | val2);

          //shift by 4 ( >> 4 )
          dstData[i + j * width] = (byte)(val >> 4);
        }
        else if (numberOfBitsUsed == 16)
        {
          // shift by 8 ( >> 8 ) is not required, just use the upper byte...
          dstData[i + j * width] = val1;
        }
      }
    }
  }

Now I am not sure of how to create a proper 8bit BitmapImage from the byte array. I tried it like this:

BitmapImage bi = null;

if (dstData != null)
  {
    bi = new BitmapImage();
    MemoryStream stream = new MemoryStream(dstData);
    stream.Seek(0, SeekOrigin.Begin);

    try
    {
      bi.BeginInit();
      bi.StreamSource = stream;
      bi.EndInit();
    }
    catch (Exception ex)
    {
      return null;
    }
  }

But I keep getting a System.NotSupportedException. How do I create a BitmapImage from a byte array correctly?

tabina

tabina
  • 1,095
  • 1
  • 14
  • 37
  • What do you get from the [PixelFormat.Mask](http://msdn.microsoft.com/en-us/library/system.windows.media.pixelformat.masks.aspx) property of the 12-bit grayscale format? – Clemens Mar 05 '13 at 16:35
  • With .Format.Masks I get 255 for the two available channels. – tabina Mar 06 '13 at 09:17
  • I just realized that if opened with the IrfanView image viewer, the image information says its a 16 bit grey image. So I guess the image was indeed created as a 16 bit image. I am using tiff images. Where in the tiff file do I have to provide the information that it is 12bit instead of 16, so that the mask will yield the correct values? – tabina Mar 06 '13 at 09:38
  • My question got answered in http://stackoverflow.com/questions/15274699/create-a-bitmapimage-from-a-byte-array – tabina Apr 04 '13 at 09:24

0 Answers0