I've got a bitmap that I want to change two colors in.
I want to change black pixels to white and vice-verse.
After iterating the bitmap one pixel at a time using getpixel and setpixel I found that it was too slow for my needs.
I found another way that I would like to try but it is a bit over my head.
Here is what I have so far:
private Bitmap SetBlackBackground(Bitmap aBmp)
{
Bitmap bmp = aBmp;
System.Drawing.Imaging.PixelFormat pxf = System.Drawing.Imaging.PixelFormat.Format32bppRgb;
Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
System.Drawing.Imaging.BitmapData bmpData =
bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite, pxf);
IntPtr ptr = bmpData.Scan0;
int numBytes = bmp.Width * bmp.Height * 3;
byte[] rgbValues = new byte[numBytes];
int g = 0;
int b = 0;
// BREAKS ON THE NEXT LINE
Marshal.Copy(ptr, rgbValues, 0, numBytes);
for (int counter = 0; counter < rgbValues.Length; counter += 3)
{
g = counter + 1;
b = counter + 2;
if ((rgbValues[counter] == 255) & (rgbValues[g] == 255) & (rgbValues[b] == 255))
{
rgbValues[counter] = 0;
rgbValues[g] = 0;
rgbValues[b] = 0;
}
else
{
if ((rgbValues[counter] == 0) & (rgbValues[g] == 0) & (rgbValues[b] == 0))
{
rgbValues[counter] = 255;
rgbValues[g] = 255;
rgbValues[b] = 255;
}
}
}
Marshal.Copy(rgbValues, 0, ptr, numBytes);
bmp.UnlockBits(bmpData);
return bmp;
}
The code breaks where indicated above.
The error says "Attempted to read or write protected memory".
This is my first encounter with "Marshal" so I'm not sure where to start looking for the error.
Don't be shy.