Here’s the code for saving a base64 encoded string to image file in C#.
You can to convert a base64 string into PNG format in C# by following code
You may also like: C# Image File to Base64 String
Base64 To PNG in C# (Save Base64 String to Png Image)
1 2 3 4 5 6 7 8 9 10 |
string base64String = File.ReadAllText(@"C:\samples\base64Image.txt"); byte[] imgBytes = Convert.FromBase64String(base64String); using (var imageFile = new FileStream(@"C:\samples\sample.png", FileMode.Create)) { imageFile.Write(imgBytes, 0, imgBytes.Length); imageFile.Flush(); } |
Base64 to BitmapImage (Convert Base64 String to Png Image)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
//my base64Image is saved in C:\samples\base64Image.txt string base64String = File.ReadAllText(@"C:\samples\base64Image.txt"); byte[] imgBytes = Convert.FromBase64String(base64String); BitmapImage bitmapImage = new BitmapImage(); MemoryStream ms = new MemoryStream(imgBytes); bitmapImage.BeginInit(); bitmapImage.StreamSource = ms; bitmapImage.EndInit(); //Image object image.Source = bitmapImage; |
Working Base64 To Image Example
MainWindow.xaml.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
public partial class MainWindow : Window { string base64String; byte[] imgBytes; public MainWindow() { InitializeComponent(); } ...... ...... ...... |
Open Base64Image Button Click
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
private void openBtn_Click(object sender, RoutedEventArgs e) { //my base64Image is saved in C:\samples\base64Image.txt base64String = File.ReadAllText(@"C:\samples\base64Image.txt"); imgBytes = Convert.FromBase64String(base64String); BitmapImage bitmapImage = new BitmapImage(); MemoryStream ms = new MemoryStream(imgBytes); bitmapImage.BeginInit(); bitmapImage.StreamSource = ms; bitmapImage.EndInit(); image.Source = bitmapImage; } |
Save Base64 To PNG button Click
1 2 3 4 5 6 7 8 9 10 11 12 13 |
private void saveBtn_Click(object sender, RoutedEventArgs e) { using (var imageFile = new FileStream(@"C:\samples\sample.png", FileMode.Create)) { imageFile.Write(imgBytes, 0, imgBytes.Length); imageFile.Flush(); } MessageBox.Show("Your base64 Code is Saved PNG"); } |
Output: