Monday, April 13, 2009

Convert Bitmap picture to Byte() and back to picture

[Not tested Code]

Let pic be the picture as
Dim pic as Bitmap

and Let bytes() be the required converted picture into byte.
Dim bytes() As Byte

Then the code to convert the picture to bytes as below:

If picture IsNot Nothing Then
Dim BitmapConverter As System.ComponentModel.TypeConverter = System.ComponentModel.TypeDescriptor.GetConverter(picture.[GetType]())
bytes= DirectCast(BitmapConverter.ConvertTo(picture, GetType(Byte())), Byte())
Else
bytes= Nothing
End If

Also to get picture back to bitmap format from the byte object the code will be like as below:

If bytes IsNot Nothing Then
pic= New Bitmap(New MemoryStream(value))
Else
pic = Nothing
End If
Uses:
The picture can't save directly in XML file and is required to be converted to like bytes only then can be saved to XML file. Similarly later it can be retrieved back to picute in bitmap format by using the above procedure.

1 comment: