Convert Image to base64

Kailash Chandra Behera | Thursday, July 30, 2020

Introduction

This blog provides the code example for convert image to base64 and base64 to image, using this you can convert png to base64, base64 to png, base64 encode image, convert png to base64, base64 string to image, etc in c#.

Getting Started

Recently I was working with an image processing project where my task was sent the image to API by converting it to base64 string and vice versa in Windows service using C#. we used to convert the png and jpg images In that application.

I thought let’s document it for further use. See the below code example details which describe how to conversion wor

Code example

To convert image to base64 and base64 to image, the image class is required which comes under the System. Drawing namespace. The MemoryStream class also required for this.

Convert Image to base64

 public string ImageToBase64()    
 {   
   string path = "D:\\SampleImage.jpg";   
   using(System.Drawing.Image image = System.Drawing.Image.FromFile(path))   
   {   
     using(MemoryStream m = new MemoryStream())   
     {   
       image.Save(m, image.RawFormat);   
       byte[] imageBytes = m.ToArray();   
       base64String = Convert.ToBase64String(imageBytes);   
       return base64String;   
     }   
   }   
 }  

convert image to base64 c#

In the above code snippet, the image is read using the FormFile method of Image class, then using the Save method the image is saved into the system memory as raw format with help of MemoryStream class. The raw formatted memory again converted into bytes, later using convert to base65String method converted the bytes to base64.

Convert base64 to Image

The reverse activity of the above section Convert image to base64 is done here, first, the string is converted into bytes using Convert.FromBase64String method then it stored into memory. Later that memory is converted into an image using the FromStream method of Image class. See the below example for more details.

 public System.Drawing.Image Base64ToImage()    
 {   
   byte[] imageBytes = Convert.FromBase64String(base64String);   
   MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);   
   ms.Write(imageBytes, 0, imageBytes.Length);   
   System.Drawing.Image image = System.Drawing.Image.FromStream(ms, true);   
   return image;   
 }  

convert base64 to image c#

Summary

In the above of this blog, we saw how to convert image to base64 and base64 to image using C#. I hope you have enjoyed it a lot.

Thanks