WPF将BitmapImage转换为12位灰色至8位灰色

时间:2013-03-05 13:52:59

标签: wpf format bitmapimage

我想将12位灰度图像转换为8位表示,以便能够正确显示它。 方法如下:

 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;
        }
      }
    }
  }

现在我不确定如何从字节数组创建一个正确的8位BitmapImage。 我试过这样的话:

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;
    }
  }

但是我一直收到System.NotSupportedException。 如何正确地从字节数组创建BitmapImage?

tabina

0 个答案:

没有答案