【问题标题】:How can I get the PixelFormat of a BitmapSource如何获取 BitmapSource 的 PixelFormat
【发布时间】:2011-06-16 14:41:44
【问题描述】:

我正在使用以下方法将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);
        }
    }
}

但我不知道如何获得BitmapSourcePixelFormat,所以我的图像被破坏了。

对于上下文,我使用这种技术是因为我想加载一个 tiff,它可能是 8 或 16 灰色或 24 或 32 位颜色,并且我需要保留 PixelFormat。我更愿意修复我的ConvertBitmapSourceToBitmap,因为它相当方便,但也很乐意用更好的技术替换以下代码,以便从 BitmapSource 创建 Bitmap:

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]);
}

【问题讨论】:

    标签: c# bitmapsource pixelformat


    【解决方案1】:

    使用BitmapSource.Format 有什么问题吗?这 PixelFormat,您已经在使用它来确定步幅。

    【讨论】:

    • 我不敢相信我没有注意到这一点。我看得太深了,我认为我已经无法使用它了!
    • 那时设计师可能应该称它为 PixelFormat。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多