开发者

How can I get the PixelFormat of a BitmapSource

开发者 https://www.devze.com 2023-03-13 06:07 出处:网络
I am using the following to convert a BitmapSource to a Bitmap: internal static Bitmap ConvertBitmapSourceToBitmap(BitmapSource bitmapSrc)

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
开发者_Python百科    {
        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.

0

精彩评论

暂无评论...
验证码 换一张
取 消