3

我想在我的 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();
}
4

1 回答 1

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
    }
于 2013-09-16T09:52:30.237 回答