Search code examples
wpfbitmapwriteablebitmap

How to avoid `WriteableBitmap buffer size is not sufficient` exception for Bgr24 format?


I want to create a WriteableBitmap and then set it as an Image.Source. I am interested only in RGB, with full opacity, so I chose the Bgr24 format.

Now when I am trying to write some pixels to the bitmap, using WritePixels() I get the Buffer size is not sufficient exception.

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

Here is my question, isn't pixelColor size (3 bytes) good enough for that operation?

Edit

It works only if I initialize the WriteableBitmap as with width and height of 1.

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

Is rects size the problem?


Solution

  • You have wrongly used x as input buffer offset, which should be zero:

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

    You may also use x and y directly as destination values, with an appropriate source rect and stride, like

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