I wrote the following methods,
public static byte[] BitmapToByteArray(Bitmap image)
{
byte[] returns = null;
if (image.PixelFormat == PixelFormat.Format8bppIndexed)
{
BitmapData bitmapData = image.LockBits(
new Rectangle(0, 0, image.Width, image.Height),
ImageLockMode.ReadWrite,
image.PixelFormat);
int noOfPixels = image.Width * image.Height;
int colorDepth = Bitmap.GetPixelFormatSize(image.PixelFormat);
int step = colorDepth / 8;
byte[] bytes = new byte[noOfPixels * step];
IntPtr address = bitmapData.Scan0;
Marshal.Copy(address, bytes, 0, bytes.Length);
returns = (byte[])bytes.Clone();
Marshal.Copy(bytes, 0, address, bytes.Length);
image.UnlockBits(bitmapData);
}
else
{
throw new Exception("8bpp indexed image required");
}
return returns;
}
And,
public static Bitmap ByteArrayToBitmap(byte[] bytes, int width, int height, PixelFormat pixelFormat)
{
Bitmap bitmap = new Bitmap(width, height, pixelFormat);
BitmapData bitmapData = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadWrite, bitmap.PixelFormat);
int colorDepth = Bitmap.GetPixelFormatSize(pixelFormat);
int noOfChannels = colorDepth / 8;
IntPtr address = bitmapData.Scan0;
Marshal.Copy(bytes, 0, address, width * height * noOfChannels);
bitmap.UnlockBits(bitmapData);
return bitmap;
}
They seem to be not working,
http://i.stack.imgur.com/e3VFD.png
What has been the problem do you think?
What I have tried:
N.B.
Driver program,
public class MainClass
{
public static void Main(string [] args)
{
Bitmap inputBmp = (Bitmap)Bitmap.FromFile(@"cameraman.gif");
byte[] bytes = Converter.BitmapToByteArray(inputBmp);
Bitmap outputBmp = Converter.ByteArrayToBitmap(bytes, inputBmp.Width, inputBmp.Height, PixelFormat.Format8bppIndexed);
PictureDisplayForm f = new PictureDisplayForm(inputBmp, outputBmp);
f.ShowDialog();
}
}