当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - How can I get the PixelFormat of a BitmapSource

问题描述:

I am using the following to convert a BitmapSource to a Bitmap:

internal static Bitmap ConvertBitmapSourceToBitmap(BitmapSource bitmapSrc)

{

int width = bitmapSrc.PixelWidth;

int height = bitmapSrc.PixelHeight;

int stride = width * ((bitmapSrc.Format.BitsPerPixel + 7) / 8);

byte[] bits = new byte[height * stride];

bitmapSrc.CopyPixels(bits, stride, 0);

unsafe

{

fixed (byte* pBits = bits)

{

IntPtr ptr = new IntPtr(pBits);

return new System.Drawing.Bitmap(

width,

height,

stride,

System.Drawing.Imaging.PixelFormat.Format32bppPArgb, //The problem

ptr);

}

}

}

But I don't know how to get the PixelFormat of the BitmapSource, so my images are mangled.

For context, I am using this technique because I want to load a tiff, which might be 8 or 16 grey or 24 or 32 bit color, and I need the PixelFormat to be preserved. I would prefer to fix my ConvertBitmapSourceToBitmap as it's rather handy, but would also be happy to replace the following code with a better technique for creating a Bitmap from a BitmapSource:

Byte[] buffer = File.ReadAllBytes(filename.FullName);

using (MemoryStream stream = new MemoryStream(buffer))

{

TiffBitmapDecoder tbd = new TiffBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);

return BitmapBitmapSourceInterop.ConvertBitmapSourceToBitmap(tbd.Frames[0]);

}

网友答案:

Anything wrong with using BitmapSource.Format? This is the PixelFormat, and you are already using it to determine the stride.

分享给朋友:
您可能感兴趣的文章:
随机阅读: