【问题标题】:How to avoid `WriteableBitmap buffer size is not sufficient` exception for Bgr24 format?如何避免 Bgr24 格式的“WriteableBitmap 缓冲区大小不足”异常?
【发布时间】:2019-10-04 14:31:47
【问题描述】:

我想创建一个WriteableBitmap,然后将其设置为Image.Source。我只对完全不透明的 RGB 感兴趣,所以我选择了Bgr24 格式。

现在,当我尝试使用 WritePixels() 将一些像素写入位图时,我得到 Buffer size is not enough 异常。

 wb = new WriteableBitmap(255, 255, 96d, 96d, PixelFormats.Bgr24, null);

            for (int x = 0; x < wb.PixelWidth; x++)
            {
                for (int y = 0; y < wb.PixelHeight; y++)
                {
                    byte blue = GetBlue();
                    byte green = GetGreen();
                    byte red = GetRed();
                    byte[] pixelColor = { blue, green, red };

                    // position where the pixel will be drawn
                    Int32Rect rect = new Int32Rect(x, y, 1, 1);
                    int stride = wb.PixelWidth * wb.Format.BitsPerPixel / 8;

                    // Write the pixel.
                    wb.WritePixels(rect, pixelColor, stride, x);
                }
            }

这是我的问题,pixelColor 的大小(3 字节)是否足以满足该操作?

编辑

只有当我将WriteableBitmap 初始化为widthheight 时,它才有效。

 wb = new WriteableBitmap(255, 255, 96d, 96d, PixelFormats.Bgr24, null); 

rects 的大小有问题吗?

【问题讨论】:

  • 步幅不是@Andy一行的字节数吗?

标签: wpf bitmap writeablebitmap


【解决方案1】:

您错误地将x 用作输入缓冲区偏移量,该偏移量应为零:

wb.WritePixels(rect, pixelColor, stride, 0);

您也可以直接使用xy 作为目标值,并带有适当的源矩形和步幅,例如

wb.WritePixels(new Int32Rect(0, 0, 1, 1), pixelColor, 3, x, y);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-04
    • 1970-01-01
    • 2012-05-13
    • 1970-01-01
    • 2020-09-05
    • 2011-04-02
    • 1970-01-01
    相关资源
    最近更新 更多