How can I get the PixelFormat of a BitmapSource
Asked Answered
H

1

7

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]);
}
Hemispheroid answered 16/6, 2011 at 14:41 Comment(0)
A
6

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

Adamsite answered 16/6, 2011 at 19:53 Comment(2)
I can't believe I didn't notice that. I was looking so deep I didn't think I could already be using it!Hemispheroid
Designers probably should've called it PixelFormat then.Willyt

© 2022 - 2024 — McMap. All rights reserved.