Sunday, December 17, 2006

A useful Image Converter for the library

Some user ask for a way to read/write images with the library.

So I create this converter that you can copy and paste in your code:

public sealed class ImageConverter: ConverterBase
public override object StringToField(string from)
Byte[] bitmapData;
bitmapData = Convert.FromBase64String(from);
System.IO.MemoryStream streamBitmap = new System.IO.MemoryStream(bitmapData);
return Image.FromStream(streamBitmap);

public override string FieldToString(object from)
Image ima = (Image) from;
System.IO.MemoryStream ms = new System.IO.MemoryStream();
ima.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
return Convert.ToBase64String(ms.ToArray());

Note: you can of course change the ImageFormat to whatever you want, I use PNG because is lost less and compress the resulting strings =)

To use this converter you need some code like:

public Image MyImage;

Easy isn't ?

Happy Coding !!


Bruce said...

You shouldn't be creating a new byte array because FromBase64String creates and returns another one, so the first one that you're creating is actually never used.

// don't create new here, useless
Byte[] bitmapData = new Byte[from.Length];

bitmapData = Convert.FromBase64String(from);

Bruce Dunwiddie

Marcos Meli said...

Ups :P

Very bad, thanks for the feedback bruce

Fixed now