Convert And Retrieve Image From Base64 Using C#

In this post, we will learn to convert and retrieve an image from base64. First, we will convert the image into base64 from a URL and second, convert the image from base64 using memory stream. The last step is to display the image in the image box using MemoryStream.
 
Here, we will use the byte array of the images for converting and retrieving the images. Follow the code written below. For this project, we are using a web application for displaying the image from base64.
 
First, we need to add the below namespace for converting the image.
  1. using System.Web;  
  2. using System.IO;  
  3. using System.Drawing; 
The second step is to get the image path.
  1. string DefaultImagePath = HttpContext.Current.Server.MapPath("~/NoImage.jpg");  
  2.   
  3. byte[] imageArray = System.IO.File.ReadAllBytes(DefaultImagePath);  
  4. string base64ImageRepresentation = Convert.ToBase64String(imageArray); 
The above code is converting the first image into byte array and then converting the byte array to base64 string. Now, the below code is converting base64 string to byte array and that converts into MemoryStream.
  1. byte[] bytes = Convert.FromBase64String(base64ImageRepresentation);  
  2.   
  3. using (MemoryStream ms = new MemoryStream(bytes))  
  4. {  
  5.     pic.Image = Image.FromStream(ms);  

The above code is converting the Base64 string into a byte array to MemoryStream and displaying the image from Stream. I am using this code in Telerik.ReportViewer for displaying the image in PictureBox.