How to Convert an image to base64 in C#

By FoxLearn 7/19/2024 2:12:20 AM   16.32K
To convert an image to a Base64 string and vice versa in a C# Windows Forms Application, you can follow these steps.

You can easily convert an image to a base64 string and vice versa in a C# Windows Forms Application using .NET Framework's built-in functionalities.

How to convert an image to base64 string and base64 string to image in C#

Open your Visual Studio, then create a new Windows Forms application project.

Next, Drag and drop the PictureBox, Label and Button controls from the Visual Studio toolbox to your winform, then design a simple UI that allows you to select an image from your disk, and then convert an image to base64 string or convert the base64 string encoded to image in c# as shown below.

convert image to base64 c#

To convert an image to base64 string, you can create a ConvertImageToBase64 method as shown below.

// c# convert image to Base64 String
public string ConvertImageToBase64(Image file)
{
    using (MemoryStream memoryStream = new MemoryStream())
    {
        file.Save(memoryStream, file.RawFormat);
        byte[] imageBytes = memoryStream.ToArray();
        return Convert.ToBase64String(imageBytes);
    }
}

The ConvertImageToBase64 read an image, then save the image into memory stream and convert to base64 string.

Similarly, to convert a base64 string encoded to an image, you can create a ConvertBase64ToImage method as shown below.

// c# convert Base64 String to image
public Image ConvertBase64ToImage(string base64String)
{
    byte[] imageBytes = Convert.FromBase64String(base64String);
    using (MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length))
    {
        ms.Write(imageBytes, 0, imageBytes.Length);
        return Image.FromStream(ms, true);
    }
}

We will convert base64 string to byte arrays, then write into memory stream, finally return an image from the stream.

Next, Click on the Image To Base64 button, then add a click event handler in c# as the following code.

//  image to base64 c#
private void btnImageToBase64_Click(object sender, EventArgs e)
{
    using (Image image = picOriginal.Image.Clone() as Image)
    {
        txtBase64.Text = ConvertImageToBase64(image);
    }
}

You can clone data from the picturebox, then cast your object to image type.

Same the way for Base64 To Image button.

// c# convert Base64 string to image
private void btnBase64ToImage_Click(object sender, EventArgs e)
{
    // Retrieve Base64 string from textbox
    picBase64ToImage.Image = ConvertBase64ToImage(txtBase64.Text);
}