Sunday, January 18, 2009

Image to byte array conversion

It's very easy to convert an image into a byte array, with VB.NET; using MemoryStream object:

Private Function ConvertImageToByteArray(ByVal inputImage As Image) As Byte()
    Dim ms As New System.IO.MemoryStream
    inputImage.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp)
    Return ms.ToArray
End Function


To re-convert the byte array into image, we can use ImageConverter class:

Private Function ConvertByteArrayToBitmap(ByVal array As Byte()) As Bitmap
    Dim ic As New ImageConverter
    Dim img As Image = CType(ic.ConvertFrom(array), Image)
    Dim bmp As New Bitmap(img)
    Return bmp
End Function

No comments: