How to Convert Base64 String to Image in C#?
To convert a Base64 string into an image in C#, we'll 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.
Let's see this in action with a simple C# program:
using System;
using System.Drawing;
using System.IO;
class Program
{
static void Main()
{
string base64String = "YOUR_BASE64_STRING_HERE";
// 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
Image image = Image.FromStream(ms);
// Output the image
image.Save("output_image.jpg");
}
Console.WriteLine("Image saved successfully.");
}
}
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 "output_image.jpg"
in the same directory as your program.
Comments (0)