WPF将位图图像12位灰色转换为8位灰色
我想将12位的灰度图像转换成8位的表示,以便能够正确显示。 以下是如何:WPF将位图图像12位灰色转换为8位灰色,wpf,format,bitmapimage,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 bytes
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;
}
}
}
}
但我一直有一个系统。不支持例外。
如何从字节数组正确创建位图图像
tabina你从12位灰度格式的属性中得到了什么?使用.format.Masks,我得到了两个可用通道的255。我刚刚意识到,如果使用IrfanView图像查看器打开,图像信息显示它是16位灰度图像。所以我猜这个图像确实是作为一个16位图像创建的。我正在使用tiff图像。在tiff文件中,我必须在哪里提供信息,即它是12位而不是16位,这样掩码才能产生正确的值?我的问题在中得到了回答
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;
}
}