How to Convert Base64 String to Image in C#?
To convert a Base64 string into an image in C#, we will follow these steps:
- Decode the Base64 string into a byte array.
- Create a memory stream from the byte array.
- Use the
Image.FromStream
method to create an image from the memory stream.
C# Program:
using System;
using System.Drawing;
using System.IO;
class Program
{
static void Main()
{
string base64String = "<YOUR_BASE64_STRING_HERE>";
try
{
// Convert Base64 string to byte array
byte[] imageBytes = Convert.FromBase64String(base64String);
// Create memory stream from byte array
using (MemoryStream ms = new MemoryStream(imageBytes))
{
// Create image from memory stream
using (Image image = Image.FromStream(ms))
{
// Save the image
image.Save("converted_image.jpg");
}
}
Console.WriteLine("Image saved successfully.");
}
catch (Exception ex)
{
Console.WriteLine("An error occurred: " + ex.Message);
}
Console.ReadKey();
}
}
Replace "YOUR_BASE64_STRING_HERE"
with your actual Base64 string. When you run this program, it will decode the Base64 string, create an image from it, and save the image as "converted_image.jpg"
in the bin/debug folder in the program.
Comments (0)