c# - 访问冲突异常保存位图
问题描述
我收到以下异常:
抛出异常:
'System.AccessViolationException' in System.Drawing.dll
调用 Bitmap 的 Save 函数时。该过程第一次运行良好,但随后的调用会引发此异常。
我的应用程序需要一个长图像并将其垂直平铺成几个单独的图像。我首先将整个图像分解为字节,然后在 Parallel.For 循环中从子集字节数组生成位图。
// Generate Bitmap from width, height and bytes
private Bitmap GenerateBitmap(int width, int height, byte[] bytes)
{
Bitmap bmp = new Bitmap(width, height, Stride(width),
PixelFormat.Format8bppIndexed,
Marshal.UnsafeAddrOfPinnedArrayElement(bytes, 0));
bmp.SetPalette();
return bmp;
}
那就是位图生成例程。
这是调用它的循环体。
Parallel.For(0, tileCount, i =>
{
byte[] bytes = new byte[imageWidth * tileHeight];
for (int j = 0; j < bytes.Length; j++)
{
bytes[j] = imageBytes[j + (imageWidth * (tileHeight * i))];
}
arr[i] = GenerateBitmap(imageWidth, tileHeight, bytes);
});
这是引发异常的其他地方的代码。
foreach(Bitmap tile in pattern.Tiles)
{
Console.WriteLine("Creating Tile " + count);
using (Bitmap bmp = new Bitmap(tile))
{
bmp.Save(Globals.patternOutputPath + "tile_" + count + ".png");
}
count += 1;
}
其中 Tiles 是调用 for 循环函数(返回位图列表)的模式的属性。
我假设我在这里的某个地方遗漏了一些清理工作。
附加信息:所有图像(输入和输出)均为 256(索引)颜色格式。
编辑:下面的评论解决了手头的问题,我认为我已经解决了这个问题。我将 GenerateBitmap 例程更改为以下内容,并且不再出现此异常,但我还有一些测试要做。
private Bitmap GenerateBitmap(int width, int height, byte[] bytes)
{
Bitmap bmp = new Bitmap(width, height, PixelFormat.Format8bppIndexed);
BitmapData bmpData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.WriteOnly, bmp.PixelFormat);
Marshal.Copy(bytes, 0, bmpData.Scan0, bytes.Length);
bmp.UnlockBits(bmpData);
return bmp;
/*Bitmap bmp = new Bitmap(width, height, Stride(width),
PixelFormat.Format8bppIndexed,
Marshal.UnsafeAddrOfPinnedArrayElement(bytes, 0));
bmp.SetPalette();
return bmp;*/
}
解决方案
推荐阅读
- angular - Angular Universal 将 favicon.ico 视为服务器端的路由
- java - 构建功能测试时出错
- reactjs - React Router 刷新 url 但不刷新页面
- java - 使用 Spring Boot 验证 Generic Rest Api
- salesforce - 无法安装@salesforce/lwc-dev-server
- excel - 从 Microsoft CSV 读取大数据并写入 AWS 中的 Microsoft Excel 的策略
- amazon-athena - LOCATION 对于 Amazon Athena 中的数据库的用途是什么?
- python - 如何在轴上绘制时间图
- android - 如何使用 SwitcpMap 观察三个数据?
- python - vscode python模块智能感知不起作用