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

3

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();
}
c#
windows-8
windows-runtime
microsoft-metro
windows-store-apps
asked on Stack Overflow Sep 16, 2013 by Farhan Ghumra

1 Answer

3

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
    }
answered on Stack Overflow Sep 16, 2013 by olydis • edited Feb 12, 2017 by olydis

User contributions licensed under CC BY-SA 3.0