I'm using the lockbit
method to manipulate an image, but I have noticed that after I save the image using the save
method of the Bitmap
type, the data that I manipulate in the byte array I get out of the lockbit, is manipulated.
For example assuming the following approach:
Bitmap bmp = new Bitmap(fs);
BitmapData bits = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, bmp.PixelFormat);
IntPtr ptr = bits.Scan0;
int arraySize = Math.Abs(bits.Stride) * bmp.Height;
Byte[] rgbValues = new Byte[arraySize];
System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, arraySize);
When I try to test this by setting all the values in the array to 0 using for example:
for(int x = 0; x < arraySize; x++){
rgbValues[x] = (Byte) (rgbValues[x] % 2 == 0 ? 0 : 1);
}
System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, ptr, arraySize);
bmp.UnlockBits(bits);
bmp.Save("somewhere");
Now when I read back the saved image using the same techniques, I see values like 10, 20, or other strange values in the obtained byte array out of the lockbit.
I don't think this can be a normal behavior, as when using the slower GetPixel
method, I do not notice such mutation.