Navigation

Wednesday, June 23, 2010

Converting Image to String and Back in Base64

When you need to store an image as string for say xml transmission you will need to transfer it back and forth from base64 encoding.

 

 

Public Function ImageToBase64(image As Image, format As System.Drawing.Imaging.ImageFormat) As String
    Using ms As New MemoryStream()
        ' Convert Image to byte[]
        image.Save(ms, format)
        Dim imageBytes As Byte() = ms.ToArray()

        ' Convert byte[] to Base64 String
        Dim base64String As String = Convert.ToBase64String(imageBytes)
        Return base64String
    End Using
End Function

 

Public Function Base64ToImage(base64String As String) As Image
    ' Convert Base64 String to byte[]
    Dim imageBytes As Byte() = Convert.FromBase64String(base64String)
    Dim ms As New MemoryStream(imageBytes, 0, imageBytes.Length)

    ' Convert byte[] to Image
    ms.Write(imageBytes, 0, imageBytes.Length)
    Dim image__1 As Image = Image.FromStream(ms, True)
    Return image__1
End Function

No comments: