0

我想将 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?

塔比纳

4

0 回答 0