Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / desktop / WinForms

Basic Base64 Encoded Image Viewer

3.03/5 (6 votes)
5 Aug 2015CPOL1 min read 20.6K   937  
VB.NET code for Base64 Encoding and Decoding of Image files

Introduction

In my recent project, I was looking for a tool to convert the Base64 Encoded string stored in my database to image and vice versa. After a lot of searching on Google, I realized that it would be faster for me to write this code and also share it with the community.

The project which I wrote is called Base64ImageViwer. The project has two core methods:

  • First method: GetImageFromBase64(ByVal Base64String) As Bitmap
  • Second method: ConvertImageToBase64(ImageInput As Image) As String

Using the Code

There are two functions in the code, one for converting Base64 string to image and the other for converting image to Base64 Encoded string. The implementation is done using a Windows Forms application in .NET 4.5 using VB.NET.

Class

Implementation of GetImageFromBase64, ConvertImageToBase64:

VB.NET
''Class for Encoding and Decoding Base64 String
Imports System.IO

Public Class Base64Codec

    ''Function to Get Image from Base64 Encoded String
    Public Function GetImageFromBase64(ByVal Base64String) As Bitmap
        Dim fileBytes As Byte()
        Dim streamImage As Bitmap
        Try
            If (String.Empty <> Base64String) Then''Checking The Base64 string validity

                fileBytes = Convert.FromBase64String(Base64String)''Convert Base64 to Byte Array

                Using ms As New MemoryStream(fileBytes)''Using Memory stream to save image

                    streamImage = Image.FromStream(ms) ''Converting image from Memory stream

                    If Not IsNothing(streamImage) Then
                        
                        ''Save image to temp path
                        streamImage.Save(Path.GetTempPath(), System.Drawing.Imaging.ImageFormat.Jpeg)

                    End If

                End Using

            End If

        Catch ex As Exception

            MsgBox(ex.Message, MsgBoxStyle.Critical, "Error")

        End Try

        Return streamImage

    End Function
    
    ''Convert the Image from Input to Base64 Encoded String
    Public Function ConvertImageToBase64(ImageInput As Image) As String

        Dim Base64Op As String = String.Empty

        Try

            Dim ms As MemoryStream = New MemoryStream()

            ImageInput.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg)''Temp saving the stream image

            Base64Op = Convert.ToBase64String(ms.ToArray())

        Catch ex As Exception

            MsgBox(ex.Message, MsgBoxStyle.Critical, "Error")

        End Try

        Return Base64Op

    End Function

End Class

This class is the implementation class for Base64 string to image and Image to Base64 string. This class is an implementation which has two public functions for Base64 string codec.

Usage

VB.NET
Imports System.IO

Public Class frmImageViwer

    Dim objBase64Codec As New Base64Codec ''Object of class Base64Codec
    Dim ButtonToolTip As New ToolTip ''Tool tip for up and down buttons

    '' Base64 to Image Converter Button click Event
    Private Sub btnDownConv_Click(sender As Object, e As EventArgs) Handles btnDownConv.Click

        Try
            ''Get the image path from Path Browsed using Browse Button

            PictureBoxImage.Image = _
            objBase64Codec.GetImageFromBase64(txtBase64Input.Text)''Decode

            txtfilename.Text = Path.GetTempPath() + _
            "\TempImg.jpg" ''Assigning a Temp Path 

        Catch ex As Exception

            MsgBox(ex.Message, MsgBoxStyle.Critical, "Error")

        End Try

    End Sub

    ''Image to Base64 Converter Button click Event
    Private Sub btnUpConv_Click(sender As Object, e As EventArgs) Handles btnUpConv.Click

        Try

            Dim ImageInput As Image = _
            Image.FromFile(txtfilename.Text) ''Getting Image from path

            txtBase64Input.Text = _
            objBase64Codec.ConvertImageToBase64(ImageInput)''Encode

        Catch ex As Exception

            MsgBox(ex.Message, MsgBoxStyle.Critical, "Error")

        End Try

    End Sub

    Private Sub btnBrowse_Click(sender As Object, e As EventArgs) Handles btnBrowse.Click

        Dim openFileDialog1 As New OpenFileDialog()''Open File Dialgoue fro Browsing file

        Try

            openFileDialog1.InitialDirectory = Path.GetTempPath()
            openFileDialog1.Filter = "jpeg files (*.jpg)|*.jpg|All files (*.*)|*.*"
            openFileDialog1.FilterIndex = 2
            openFileDialog1.RestoreDirectory = True

            If openFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then

                txtfilename.Text = openFileDialog1.FileName
                PictureBoxImage.Image = _
                Image.FromFile(txtfilename.Text)''Setting Image of Picture Box

            End If

        Catch ex As Exception

            MsgBox(ex.Message, MsgBoxStyle.Critical, "Error")

        End Try

    End Sub

   ''For Deleting Temp file created
    Private Sub ClearFile()

        Try

            Dim TempFile As String = Path.GetTempPath() + "\TempImg.jpg"
            File.Delete(TempFile) 

        Catch ex As Exception

            MsgBox(ex.Message, MsgBoxStyle.Critical, "Error")

        End Try

    End Sub

    Private Sub frmImageViwer_FormClosed_
    (sender As Object, e As FormClosedEventArgs) Handles MyBase.FormClosed
        ClearFile()

    End Sub

    ''For making Textbox Select All enable
    Private Sub txtBase64Input_KeyPress_
    (sender As Object, e As KeyPressEventArgs) Handles txtBase64Input.KeyPress
        If Asc(e.KeyChar) = 1 Then
            With txtBase64Input
                .SelectionStart = 0
                .SelectionLength = Len(.Text)
                e.Handled = True
            End With

        End If

    End Sub

    ''Show Tool Tip Text on Mouse Enter
    Private Sub btnUpConv_MouseEnter_
    (sender As Object, e As EventArgs) Handles btnUpConv.MouseEnter

        ButtonToolTip.Show("Convert Image to Base64", btnUpConv, 30, 0, 1000)

    End Sub

     ''Show Tool Tip Text on Mouse Enter
    Private Sub btnDownConv_MouseEnter_
    (sender As Object, e As EventArgs) Handles btnDownConv.MouseEnter

        ButtonToolTip.Show("Convert Base64 to Image", btnDownConv, 30, 1, 1000)

    End Sub

End Class

The Windows Form implementation has two buttons, a down arrow button which is used to convert Base64 Encoded string to Image and show that image in picture box, any errors in string will throw an exception in a message box and another button is up arrow button which is used to convert image in picture box to Base64 string. The image is browsed using the browse button which will pop up a file browser. This version of the code only supports .jpeg image files. The two buttons have a tooltip text. A temp path is assigned for saving the image temporarily after the form is closed, then temp file is deleted.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)