“The buffer allocated is insufficient” exception while calling BitmapEncoder.SetPixelData

隐身守侯 提交于 2019-12-10 19:00:15

问题


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

回答1:


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
    }


来源:https://stackoverflow.com/questions/18824873/the-buffer-allocated-is-insufficient-exception-while-calling-bitmapencoder-set

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!