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. :)