Convert an Image to Base64 String and Base64 String to Image

In this blog we will learn about that how to convert an Image to Base64 string and Base64 String to Image.

Base64 encoding is commonly used when there is a requirement to convert binary data to string format. Base64 is commonly used in a number of applications, including email via MIME, and storing complex data in XML.

Let see how to convert an Image to Base64 string and Base64 String to Image.

Code Snippet

Default.aspx 

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>  
  2. <!DOCTYPE html>  
  3. <html  
  4.     xmlns="http://www.w3.org/1999/xhtml">  
  5.     <head runat="server">  
  6.         <title></title>  
  7.     </head>  
  8.     <body>  
  9.         <form id="form1" runat="server">  
  10.             <asp:Button ID="Button1" runat="server" OnClick="ImageToBase_Click" Text="Image to Base64" />  
  11.             <asp:TextBox ID="TextBox1" runat="server" Height="146px" TextMode="MultiLine"></asp:TextBox>  
  12.             <br />  
  13.             <asp:Button ID="Button2" runat="server" OnClick="BaseToImage_Click" Text="Base64 To Image" />  
  14.             <asp:Image ID="Image1" runat="server" Height="157px" style="margin-top: 0px; margin-right: 4px;" Width="168px" />  
  15.         </form>  
  16.     </body>  
  17. </html>  
Default.aspx.cs 
  1. static string base64String = null;  
  2. public string ImageToBase64()   
  3. {  
  4.     string path = "D:\\SampleImage.jpg";  
  5.     using(System.Drawing.Image image = System.Drawing.Image.FromFile(path))  
  6.     {  
  7.         using(MemoryStream m = new MemoryStream())  
  8.         {  
  9.             image.Save(m, image.RawFormat);  
  10.             byte[] imageBytes = m.ToArray();  
  11.             base64String = Convert.ToBase64String(imageBytes);  
  12.             return base64String;  
  13.         }  
  14.     }  
  15. }  
  16. public System.Drawing.Image Base64ToImage()   
  17. {  
  18.     byte[] imageBytes = Convert.FromBase64String(base64String);  
  19.     MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);  
  20.     ms.Write(imageBytes, 0, imageBytes.Length);  
  21.     System.Drawing.Image image = System.Drawing.Image.FromStream(ms, true);  
  22.     return image;  
  23. }  
  24. protected void ImageToBase_Click(object sender, EventArgs e)   
  25. {  
  26.     TextBox1.Text = ImageToBase64();  
  27. }  
  28. protected void BaseToImage_Click(object sender, EventArgs e)  
  29. {  
  30.     Base64ToImage().Save(Server.MapPath("~/Images/Hello.jpg"));  
  31.     Image1.ImageUrl = "~/Images/Hello.jpg";  
  32. }  
Note : First Click on “Image to Base64” Button then we can see Base64 string in textbox, then click on “Base64 to Image” Button to see the Image from Base64 string.