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.
- using System.Web;
- using System.IO;
- using System.Drawing;
The second step is to get the image path.
- string DefaultImagePath = HttpContext.Current.Server.MapPath("~/NoImage.jpg");
-
- byte[] imageArray = System.IO.File.ReadAllBytes(DefaultImagePath);
- 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.
- byte[] bytes = Convert.FromBase64String(base64ImageRepresentation);
-
- using (MemoryStream ms = new MemoryStream(bytes))
- {
- 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.