如何获取 BitmapSource 的 PixelFormat
我正在使用以下内容将 BitmapSource
转换为 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);
}
}
}
但我不知道如何获取 的
,所以我的图像被破坏了。PixelFormat
BitmapSource
对于上下文,我使用此技术是因为我想加载 tiff,它可能是 8 或 16 灰度或 24 或 32 位颜色,并且我需要保留 PixelFormat
。我更愿意修复我的 ConvertBitmapSourceToBitmap
因为它相当方便,但也很乐意用更好的技术替换以下代码,以从 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]);
}
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]);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用 BitmapSource.Format?这是 PixelFormat,您已经在使用它来确定步幅。
Anything wrong with using BitmapSource.Format? This is the PixelFormat, and you are already using it to determine the stride.