AccessViolationException

AccessViolationException

我有一个功能,可以从像素阵列生成图像并将其保存到文件中。一次调用就可以正常工作。但是,如果我两次调用它(第一次完全执行之后),该函数将抛出AccessViolationException

private void saveImage(byte[] bmpBytes)
{
    Debug.Print("Image saving started");

    var arrayHandle = System.Runtime.InteropServices.GCHandle.Alloc(bmpBytes, System.Runtime.InteropServices.GCHandleType.Pinned);
    System.Drawing.Image bmp = new System.Drawing.Bitmap(960, 540, 960 * 3, PixelFormat.Format24bppRgb, arrayHandle.AddrOfPinnedObject());
    bmp.Save("img.bmp");

    Debug.Print("Image saving completed");
}


因此,bmp.Save("img.bmp");行会引发异常。我也尝试过将数据保存在MemoryStream中,但结果相同:第一次调用成功,每隔AccessViolationException次成功。是什么原因呢?

最佳答案

此错误表明您正在尝试访问受保护的内存。您最有可能通过了一个数组,数组的大小小于所需的图像大小。它类似于缓冲区溢出。因此,当GDI尝试用映像读取内存时,它超出了为进程内存分配的容量,并发生了故障。顺便说一句,行为是不确定的。例如,如果该内存已分配给某个进程,则您将读取该进程拥有的任何内容,并且不会收到任何错误。在这种情况下,您很可能会看到带有一些噪点的图像。

您确定要传递有效长度的数组吗?尝试添加相应的检查。并且不要忘记释放分配的内存-GCHandle must be released with Free when it is no longer needed

只需运行该代码,就不会出错:

int width = 960;
int height = 540;

void Main()
{
    var arr = Enumerable.Range(0, width * height * 3).Select(i =>
    {
        i = i / 3;
        var y = i / width;
        var x = i - y * width;
        var xd = x / (double)(width - 1);
        var yd = y / (double)(height - 1);
        return (byte)((xd + yd) / 2d * 255);
    }).ToArray();
    saveImage2(arr);
}

private void saveImage2(byte[] bmpBytes)
{
    if (bmpBytes == null)
        throw new ArgumentNullException("bmpBytes");

    if (bmpBytes.Length != width * height * 3)
        throw new ArgumentException("Invalid array length", "bmpBytes");

    var output = new Bitmap(width, height, PixelFormat.Format24bppRgb);
    var rect = new Rectangle(0, 0, width, height);
    var bmpData = output.LockBits(rect, ImageLockMode.WriteOnly, output.PixelFormat);

    // Stride must be taken into account.
    // Actual row length may be greater then required due to GDI's internal memory alignment.
    // It is an error to copy entire array as-is, need to copy row-by-row.
    var rowBytes = width * Image.GetPixelFormatSize(output.PixelFormat) / 8;
    var ptr = bmpData.Scan0;
    for (var i = 0; i < height; i++)
    {
        Marshal.Copy(bmpBytes, i * rowBytes, ptr, rowBytes);
        ptr += bmpData.Stride;
    }

    output.UnlockBits(bmpData);

    output.Save(@"d:\temp\img.bmp");
}

10-05 18:45