Friday, June 04, 2010

Bitmap Serialize

So I've been tasked to fix a database full of pictures that weren't displayed, no matter what I tried, the Image (Stored as a byte array) was always invalid.

So I thought I'll save the file and see if I can get an image fixer on it, I just used a FileStream opened it and wrote to it


var fileStream = new FileStream("output.dat", System.IO.FileMode.Create);
fileStream.Write(bytes, 0, bytes.Length);
fileStream.Close();


Upon opening the file, I was expected to see something beginning with "Exif" or "JPG" or something, but what I saw was even better.


System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a


A, ha!! The actual Bitmap object was being saved, not the actual Image, therefore I put together a bit of code to get me the Image and put it back as the Image for my code to work correctly. In this case, I could fix it, but if I couldn't I'd have to have a bit of a legacy converter for it.



public static Bitmap BitmapObjectToBitmap(byte[] data)
{
using (var ms = new MemoryStream(data))
{
var bf = new BinaryFormatter();
Bitmap bitmap = (Bitmap)bf.Deserialize(ms);
return bitmap;
}
}


Then the working code for the Image to Byte Array



public static byte[] ImageToByteArray(Image image, ImageFormat format)
{
using (var ms = new MemoryStream())
{

var bm = new Bitmap(image);
bm.Save(ms, format);
return ms.ToArray();

}
}



Comments welcome!!

0 comments:

Post a Comment