In the code below I want to convert an image to a byte array, modify the value of some pixels, and convert it back to an image. Everything works fine if I don't modify any pixel value. The two conversions work. But if I try to modify a pixel value between the two conversions I get an exception. Can you tell me what I am doing wrong ?
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.ShowDialog();
FileStream bmpstream = new FileStream(openFileDialog.FileName, FileMode.Open, FileAccess.Read);
Bitmap spotImage = new Bitmap(bmpstream);
ImageConverter imgCon = new ImageConverter();
byte[] rgbValues = (byte[])imgCon.ConvertTo(spotImage, typeof(byte[]));
for (int counter = 2; counter < rgbValues.Length; counter += 3)
{
Buffer.SetByte(rgbValues, counter, 0x00);
//rgbValues[counter] = 0x00; <--I tried also this (not sure of the difference) and I get the same result
}
Image image2 = null;
using (MemoryStream mStream = new MemoryStream(rgbValues, 0, rgbValues.Length))
{
image2 = Image.FromStream(mStream, true); //this line gives the exception
}
pictureBox2.Image = image2;
I also tried to open the file using Bitmap.LockBits and got the same result. Here is the second version of the code (again, it worked as long as I didn't modify the byte array):
Rectangle rect = new Rectangle(0, 0, spotImage.Width, spotImage.Height);
BitmapData bmpData = spotImage.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadOnly, spotImage.PixelFormat);
IntPtr pointeur = bmpData.Scan0;
int bytes = Math.Abs(bmpData.Stride) * bmpData.Height;
byte[] rgbValues = new byte[bytes];
System.Runtime.InteropServices.Marshal.Copy(pointeur, rgbValues, 0, bytes);
for (int counter = 2; counter < rgbValues.Length; counter += 3)
{
Buffer.SetByte(rgbValues, counter, 0x00);
//rgbValues[counter] = 0x00;
}
spotImage.UnlockBits(bmpData);
Image image2 = null;
using (MemoryStream mStream = new MemoryStream(rgbValues, 0, rgbValues.Length))
{
image2 = Image.FromStream(mStream, true); //this line gives the exception
}
pictureBox2.Image = image2;