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]);
}
BitmapSource has a CopyPixelsmethod that can be used to get one or more pixel values. A helper method that gets a single pixel value at a given pixel coordinate may look like shown below. Note that it perhaps has to be extended to support all required pixel formats. public static Color GetPixelColor(BitmapSource bitmap, int x, int y)
This example demonstrates how to convert a BitmapSource object ( BitmapImage) to a different PixelFormat using a FormatConvertedBitmap. ///// Create a BitmapImage and set it's DecodePixelWidth to 200. Use ///// ///// this BitmapImage as a source for other BitmapSource objects.
More sophisticated classes derived from BitmapSource deal with the problem of getting from a format such as JPEG to the raw pixel data. However, if you have a class that can read in a bitmap format and decode it to the point where you have an array of bytes representing the pixels then you can use a BitmapSource to encapsulate it.
However, if you have a class that can read in a bitmap format and decode it to the point where you have an array of bytes representing the pixels then you can use a BitmapSource to encapsulate it.
Anything wrong with using BitmapSource.Format? This is the PixelFormat, and you are already using it to determine the stride.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With