How can I get PixelFormat BitmapSource

To convert a BitmapSource to Bitmap use the following:

 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 PixelFormat from BitmapSource , so my images are distorted.

In the context, I use this method because I want to load tiff, which can be 8 or 16 gray or 24 or 32-bit color, and I need to save the PixelFormat . I would prefer to fix my ConvertBitmapSourceToBitmap as it is quite convenient, but would also be happy to replace the following code with the best Bitmap creation method from 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]); } 
+6
source share
1 answer

Is there something wrong with using BitmapSource.Format ? This is a PixelFormat, and you are already using it to determine the step.

+4
source

Source: https://habr.com/ru/post/890686/


All Articles