Convert image to string

Convert image to base64 encoded string and vice versa. Like Resource.resx file does. Can be used with settings file.

    'usage
    Private Sub saveImageToSettings()
        My.Settings.imageSettingAsString = getBase64String(PictureBox1.Image)
        My.Settings.Save()
    End Sub

    Private Sub getImageFromString()
        PictureBox1.Image = getImageFromBase64String(My.Settings.imageSettingAsString)
    End Sub

    'Functions
    Private Function getBase64String(ByVal bmp As Image) As String
        'convert image to base64 encoded string
        Dim ms As New MemoryStream
        Dim bytes() As Byte
        bmp.Save(ms, Imaging.ImageFormat.Jpeg)
        bytes = ms.GetBuffer
        Return Convert.ToBase64String(bytes)
    End Function

    Private Function getImageFromBase64String(ByVal base64String As String) As Bitmap
        'convert base64 encoded string to image
        Dim bytes() As Byte = Convert.FromBase64String(base64String)
        Dim ms As New MemoryStream()
        ms.Write(bytes, 0, bytes.Length - 1)
        Return New Bitmap(ms)
    End Function
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s