Search code examples
c#windows-8windows-runtimemicrosoft-metrowindows-store-apps

"The buffer allocated is insufficient" exception while calling BitmapEncoder.SetPixelData


I want to create a white image run time in my Windows 8 app. I thought I will create a byte array and then will write onto file. But I am getting exception The buffer allocated is insufficient. (Exception from HRESULT: 0x88982F8C). What's wrong with my code?

double dpi = 96;
int width = 128;
int height = 128;
byte[] pixelData = new byte[width * height];

for (int y = 0; y < height; ++y)
{
    int yIndex = y * width;
    for (int x = 0; x < width; ++x)
    {
        pixelData[x + yIndex] = (byte)(255);
    }
}

var newImageFile = await ApplicationData.Current.TemporaryFolder.CreateFileAsync("white.png", CreationCollisionOption.GenerateUniqueName);

using (IRandomAccessStream newImgFileStream = await newImageFile.OpenAsync(FileAccessMode.ReadWrite))
{

    BitmapEncoder bmpEncoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, newImgFileStream);

    bmpEncoder.SetPixelData(
        BitmapPixelFormat.Bgra8,
        BitmapAlphaMode.Premultiplied,
        (uint)width,
        (uint)height,
        dpi,
        dpi,
        pixelData);

    await bmpEncoder.FlushAsync();
}

Solution

  • Be careful with your BitmapPixelFormat!

    BitmapPixelFormat.Bgra8 means 1 byte per channel, resulting in 4 bytes per pixel - you are calculating with 1 byte per pixel. (more info: http://msdn.microsoft.com/en-us/library/windows/apps/windows.graphics.imaging.bitmappixelformat.ASPx)

    So increase your buffer size accordingly. ;)

    Sample code:

    int width = 128;
    int height = 128;
    byte[] pixelData = new byte[4 * width * height];
    
    int index = 0;
    for (int y = 0; y < height; ++y)
        for (int x = 0; x < width; ++x)
        {
            pixelData[index++] = 255;  // B
            pixelData[index++] = 255;  // G
            pixelData[index++] = 255;  // R
            pixelData[index++] = 255;  // A
        }