c# Attempted to read write protected memory Bitmap

Viewed 538

I am simply trying to copy one Bitmap into another, and change color values. I'm always getting same exception

An unhandled exception of type 'System.AccessViolationException' occurred in Project.exe Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

The error always occurs when the value of the mm reaches 512 and m is 0. Here is the code:

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 Answers
Related