调用BitmapEncoder.SetPixelData时,“分配的缓冲区不足”异常

时间:2013-09-16 09:42:20

标签: c# windows-8 windows-runtime microsoft-metro windows-store-apps

我想在Windows 8应用中创建白色图像运行时。我以为我会创建一个字节数组然后写入文件。但我得到例外The buffer allocated is insufficient. (Exception from HRESULT: 0x88982F8C)。我的代码出了什么问题?

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 个答案:

答案 0 :(得分:3)

小心BitmapPixelFormat

BitmapPixelFormat.Bgra8表示每个通道1个字节 ,每个像素产生4个字节 - 您计算每个像素1个字节。 (更多信息:http://msdn.microsoft.com/en-us/library/windows/apps/windows.graphics.imaging.bitmappixelformat.ASPx

因此相应地增加缓冲区大小。 ;)

示例代码:

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
    }