c# - 调用 BitmapEncoder.SetPixelData 时出现 "The buffer allocated is insufficient"异常

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

我想在我的 Windows 8 应用程序中创建一个白色图像运行时。我想我会创建一个字节数组,然后写入文件。但我收到异常 分配的缓冲区不足。 (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();
}

最佳答案

小心你的BitmapPixelFormat!

BitmapPixelFormat.Bgra8 表示 每个 channel 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
    }

关于c# - 调用 BitmapEncoder.SetPixelData 时出现 "The buffer allocated is insufficient"异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18824873/

相关文章:

c# - Puppeteer Sharp html 到 pdf 并启用链接

c# - 图钉调整绑定(bind)缩放级别大小

安装新的 C++ 重新分发包后,C++ 运行时行为异常

c# - VS2013 - 如何使用外部程序在 C# 项目的命令行参数中传递解决方案文件夹 $(SolutionDir)

c# - datagridview即使没有数据c#也可见网格线

c# - WPF C# 应用程序中的哈希密码

c# - 作为聚合异常抛出的自定义异常

xaml - Windows 8 主题颜色 - 以编程方式访问它

Java Windows 8 全屏?

c# - System.Net.Http.Handlers.ProgressMessageHandler 立即返回 100%