Convert Images to Base64 Strings

Introduction

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.

Here in this article I have created a service which will first resize images then convert images in base64 strings and then will return base64 images in JSON format.

Let’s go thru the demonstration.

Create service

Service1.svc.cs

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Runtime.Serialization;  
  5. using System.ServiceModel;  
  6. using System.ServiceModel.Web;  
  7. using System.Text;  
  8. using System.IO;  
  9. using System.Drawing;  
  10. using System.Drawing.Imaging;  
  11. namespace PhotoService   
  12. {  
  13.     public class Service1: IService1   
  14.     {  
  15.         static string[] ImageBase64Strings;  
  16.         static int ImageCounts;  
  17.         static string[] base64Value;  
  18.         DirectoryInfo di;  
  19.         System.Drawing.Image imgThumb = null;  
  20.         int thumbWidth = 100;  
  21.         int thumbHeight = 100;  
  22.         Service1() {  
  23.             di = new DirectoryInfo(@  
  24.             "D:\ImageFolder"); // Path of images  
  25.             ImageCounts = di.GetFiles("*.jpg", SearchOption.TopDirectoryOnly).Length;  
  26.             base64Value = new string[ImageCounts];  
  27.         }  
  28.         public string[] GetImages() //This method will return base64 strings in JSON format  
  29.         {  
  30.             try   
  31.             {  
  32.                 int i = 0;  
  33.                 FileInfo[] finfos = di.GetFiles("*.jpg", SearchOption.TopDirectoryOnly);  
  34.                 ImageBase64Strings = new string[ImageCounts];  
  35.                 foreach(FileInfo fi in finfos)   
  36.                 {  
  37.                     using(System.Drawing.Image img = System.Drawing.Image.FromFile(fi.FullName)) {  
  38.                         imgThumb = CreateThumbnail(img, thumbWidth, thumbHeight);  
  39.                         using(MemoryStream m = new MemoryStream())   
  40.                         {  
  41.                             imgThumb.Save(m, ImageFormat.Jpeg);  
  42.                             byte[] imageBytes = m.ToArray();  
  43.                             ImageBase64Strings[i] = Convert.ToBase64String(imageBytes);  
  44.                             i++;  
  45.                         }  
  46.                     }  
  47.                 }  
  48.                 return ImageBase64Strings;  
  49.             } catch (Exception ex)   
  50.             {  
  51.                 throw ex;  
  52.             }  
  53.         }  
  54.         private Image CreateThumbnail(Image image, int thumbWidth, int thumbHeight)  
  55.         {  
  56.             try   
  57.             {  
  58.                 return image.GetThumbnailImage(  
  59.                 thumbWidth,  
  60.                 thumbHeight,  
  61.                 delegate()   
  62.                 {  
  63.                     return false;  
  64.                 },  
  65.                 IntPtr.Zero);  
  66.             } catch (Exception ex)  
  67.             {  
  68.                 throw ex;  
  69.             }  
  70.         }  
  71.         public Stream ToStream(Image image, ImageFormat formaw)  
  72.         {  
  73.             try  
  74.             {  
  75.                 var stream = new System.IO.MemoryStream();  
  76.                 image.Save(stream, formaw);  
  77.                 stream.Position = 0;  
  78.                 return stream;  
  79.             } catch (Exception ex)   
  80.             {  
  81.                 throw;  
  82.             }  
  83.         }  
  84.     }  
  85. }  
IService1.cs
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Runtime.Serialization;  
  5. using System.ServiceModel;  
  6. using System.ServiceModel.Web;  
  7. using System.Text;  
  8. using System.IO;  
  9. using System.Drawing;  
  10. using System.Drawing.Imaging;  
  11. namespace PhotoService  
  12. {  
  13.     [ServiceContract]  
  14.     public interface IService1   
  15.     {  
  16.         [OperationContract]  
  17.         [WebGet(UriTemplate = "/GetImages", RequestFormat = WebMessageFormat.Json,  
  18.         ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]  
  19.         string[] GetImages();  
  20.     }  
  21. }  
Web Application to consume web service

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.             <div>  
  11.                 <asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="Get Images from Base64 strings" />  
  12.                 <br />  
  13.                 <asp:Repeater ID="FileRepeater" runat="server">  
  14.                     <ItemTemplate>  
  15.                         <asp:Image ID="Image1" runat="server" ImageUrl="  
  16.                             <%# Container.DataItem %>/>  
  17.                         </ItemTemplate>  
  18.                     </asp:Repeater>  
  19.                 </div>  
  20.             </form>  
  21.         </body>  
  22.     </html>  
Default.aspx.cs
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7. using System.Runtime.Serialization;  
  8. using System.Net;  
  9. using System.IO;  
  10. using System.Xml.Linq;  
  11. using System.Xml;  
  12. using System.Runtime.Serialization.Json;  
  13. public partial class _Default: System.Web.UI.Page   
  14. {  
  15.     protected void Page_Load(object sender, EventArgs e) {}  
  16.     static int count = 0;  
  17.     protected void Button2_Click(object sender, EventArgs e)   
  18.     {  
  19.         try   
  20.         {  
  21.             HttpWebRequest request = WebRequest.Create("http://localhost:21269/Service1.svc/GetImages"as HttpWebRequest;  
  22.             using(HttpWebResponse response = request.GetResponse() as HttpWebResponse) {  
  23.                 if (response.StatusCode != HttpStatusCode.OK) throw new Exception(String.Format("Server error (HTTP {0}: {1}).", response.StatusCode, response.StatusDescription));  
  24.                 DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(string[]));  
  25.                 object objResponse = jsonSerializer.ReadObject(response.GetResponseStream());  
  26.                 string[] data = objResponse as string[];  
  27.                 count = data.Length;  
  28.                 System.Drawing.Image[] Converted_Image = new System.Drawing.Image[count];  
  29.                 Converted_Image = Base64ToImage(data);  
  30.                 for (int i = 0; i < count; i++)  
  31.                 {  
  32.                     string filename = Server.MapPath("~/Images/" + i + ".jpg");  
  33.                     Converted_Image[i].Save(filename);  
  34.                 }  
  35.                 string[] list = Directory.GetFiles(Server.MapPath("~/Images"));  
  36.                 var aList = from fileName in Directory.GetFiles(Server.MapPath("~/Images")) select string.Format("~/Images/{0}", Path.GetFileName(fileName));  
  37.                 FileRepeater.DataSource = aList;  
  38.                 FileRepeater.DataBind();  
  39.             }  
  40.         } catch (Exception ex)   
  41.         {  
  42.             Response.Write("Error : " + ex.Message);  
  43.         }  
  44.     }  
  45.     public System.Drawing.Image[] Base64ToImage(string[] base64String)   
  46.     {  
  47.         System.Drawing.Image[] image = new System.Drawing.Image[count];  
  48.         for (int i = 0; i < count; i++)  
  49.         {  
  50.             byte[] imageBytes = Convert.FromBase64String(base64String[i]);  
  51.             MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);  
  52.             ms.Write(imageBytes, 0, imageBytes.Length);  
  53.             image[i] = System.Drawing.Image.FromStream(ms, true);  
  54.         }  
  55.         return image;  
  56.     }  
  57. }