c#尝试读取写保护的内存Bitmap

时间:2016-03-14 19:32:35

标签: c# bitmap

我只是想将一个Bitmap复制到另一个,并更改颜色值。我总是得到同样的异常

  

未处理的类型' System.AccessViolationException'发生在Project.exe中   附加信息:尝试读取或写入受保护的内存。这通常表明其他内存已损坏。

当mm的值达到512且m为0时,始终会发生错误。以下是代码:

public void PrintYBitmapUnsafe()
{
    YBitmap = (Bitmap)myBitmap.Clone();
    BitmapData bmData = this.myBitmap.LockBits(new Rectangle(0, 0, myBitmap.Width, myBitmap.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
    BitmapData bmData1 = YBitmap.LockBits(new Rectangle(0, 0, YBitmap.Width, YBitmap.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
    int stride = bmData.Stride;
    System.IntPtr scan0 = bmData.Scan0;
    System.IntPtr scan00=bmData1.Scan0;
    unsafe
    {
        int offset = stride - myBitmap.Width * 3;
        int offset1 = bmData1.Stride - YBitmap.Width * 3;
        int pixelRowLength = myBitmap.Width * 3;
        byte* pp = (byte*)(void*)scan00;
        byte* p = (byte*)(void*)scan0;
        Object thisLock = new Object();
        for (int y = 0; y < myBitmap.Height; y++)
        {
            for (int x = 0; x < pixelRowLength; ++x)
            {
                int m = x;
                int mm = y;
                double pixelY = p[0] * 0.114;
                pixelY += p[1] * 0.587;
                pixelY += p[2] * 0.29;

                pp[0] = (byte)Math.Floor(pixelY);
                pp[1] = (byte)Math.Floor(pixelY);
                pp[2] = (byte)Math.Floor(pixelY);
                p = p + 3;
                pp = pp + 3;
            }
            pp = pp + offset1;
            p = p + offset;
        }
    }
    myBitmap.UnlockBits(bmData);
    YBitmap.UnlockBits(bmData1);
}

0 个答案:

没有答案