Question

I'm getting this error when using the code below to access the pixel data of three different bitmaps:

Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

C# code:

var bmpDataA = bitmap.LockBits(bounds, ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
var bmpDataB = bitmap2.LockBits(bounds, ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
var bmpDataC = bitmap3.LockBits(bounds, ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);

const int width = 1280;
const int height = 720;
int npixels = width * height;

unsafe
{
    int* pPixelsA = (int*)bmpDataA.Scan0.ToPointer();
    int* pPixelsB = (int*)bmpDataB.Scan0.ToPointer();
    int* pPixelsC = (int*)bmpDataC.Scan0.ToPointer();

    for (int i = 0; i < npixels; ++i)
    {
        if (pPixelsA[i] == pPixelsB[i]) // <--- Error occurs on this line
        {
            pPixelsC[i] = Color.Black.ToArgb();
        }
    }
}
bitmap.UnlockBits(bmpDataA);
bitmap2.UnlockBits(bmpDataB);
bitmap3.UnlockBits(bmpDataC);

Using the debugger I can see that the variable npixels = 921600 and when the error happens the (for loop) variable i = 691200. So not sure what the problem is. If I change the pixel format to 32bppRgb there's no problem and it works fine. Just doesn't want to work with 24bppRgb. Any ideas? Thanks. :)

Was it helpful?

Solution

  1. PixelFormat.Format24bppRgb mean 24 bit = 3 byte on each pixel, therefore, method LockBits locks 1280 * 720 * 3 = 2764800 bytes

  2. You cast pointer on locked data to int*. Size of int = 32 bit = 4 byte.

  3. Therefore, you are trying to process 1280 * 720 * 4 = 3686400 bytes, whereas you have lock 2764800 (see 1). Mismatch.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top