How Do You Convert an Image to Base64 Using C#

Jan 27, 2024

2 mins read

Published in

Converting Base64 to Image in C#: A Comprehensive Guide with Working Code

Base64 encoding is a common technique for representing binary data as a string of ASCII characters. In C#, you may come across scenarios where you need to convert a Base64 string to an image. In this blog post, we’ll explore the process step by step and provide a working code example.

1. Understanding Base64 Encoding:

Base64 encoding is a method of encoding binary data into ASCII text, making it easier to transmit over text-based protocols like JSON or XML. The encoded string typically starts with “data:image/{format};base64,” where “{format}” is the image format (e.g., “png” or “jpeg”).

2. Decoding Base64 to Byte Array:

To convert a Base64 string to an image, we first need to decode the Base64 string into a byte array. This can be achieved using the Convert.FromBase64String method in C#.

1
2
string base64String = "your_base64_string_here";
byte[] imageBytes = Convert.FromBase64String(base64String);

3. Creating an Image from Byte Array:

Once we have the byte array, we can create an image from it. This can be done using a MemoryStream and the Image.FromStream method.

1
2
3
4
5
using (MemoryStream ms = new MemoryStream(imageBytes))
{
    Image image = Image.FromStream(ms);
    // Now 'image' contains the decoded image.
}

4. Saving the Image (Optional):

If you need to save the image to a file, you can use the Save method.

1
image.Save("path_to_save_image/image.png", ImageFormat.Png);

5. Putting it All Together:

Now, let’s combine the above steps into a working example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;

class Program
{
    static void Main()
    {
        string base64String = "your_base64_string_here";

        // Decode Base64 to byte array
        byte[] imageBytes = Convert.FromBase64String(base64String);

        // Create image from byte array
        using (MemoryStream ms = new MemoryStream(imageBytes))
        {
            Image image = Image.FromStream(ms);

            // Optional: Save the image
            image.Save("path_to_save_image/image.png", ImageFormat.Png);

            Console.WriteLine("Image conversion successful!");
        }
    }
}

In this blog post, we’ve explored how to convert a Base64 string to an image in C#. Understanding Base64 encoding, decoding it to a byte array, and creating an image from the byte array are crucial steps in achieving this. The provided C# code snippet demonstrates a simple and effective way to perform this conversion.

Sharing is caring!