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
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Runtime.Serialization;
- using System.ServiceModel;
- using System.ServiceModel.Web;
- using System.Text;
- using System.IO;
- using System.Drawing;
- using System.Drawing.Imaging;
- namespace PhotoService
- {
- public class Service1: IService1
- {
- static string[] ImageBase64Strings;
- static int ImageCounts;
- static string[] base64Value;
- DirectoryInfo di;
- System.Drawing.Image imgThumb = null;
- int thumbWidth = 100;
- int thumbHeight = 100;
- Service1() {
- di = new DirectoryInfo(@
- "D:\ImageFolder");
- ImageCounts = di.GetFiles("*.jpg", SearchOption.TopDirectoryOnly).Length;
- base64Value = new string[ImageCounts];
- }
- public string[] GetImages()
- {
- try
- {
- int i = 0;
- FileInfo[] finfos = di.GetFiles("*.jpg", SearchOption.TopDirectoryOnly);
- ImageBase64Strings = new string[ImageCounts];
- foreach(FileInfo fi in finfos)
- {
- using(System.Drawing.Image img = System.Drawing.Image.FromFile(fi.FullName)) {
- imgThumb = CreateThumbnail(img, thumbWidth, thumbHeight);
- using(MemoryStream m = new MemoryStream())
- {
- imgThumb.Save(m, ImageFormat.Jpeg);
- byte[] imageBytes = m.ToArray();
- ImageBase64Strings[i] = Convert.ToBase64String(imageBytes);
- i++;
- }
- }
- }
- return ImageBase64Strings;
- } catch (Exception ex)
- {
- throw ex;
- }
- }
- private Image CreateThumbnail(Image image, int thumbWidth, int thumbHeight)
- {
- try
- {
- return image.GetThumbnailImage(
- thumbWidth,
- thumbHeight,
- delegate()
- {
- return false;
- },
- IntPtr.Zero);
- } catch (Exception ex)
- {
- throw ex;
- }
- }
- public Stream ToStream(Image image, ImageFormat formaw)
- {
- try
- {
- var stream = new System.IO.MemoryStream();
- image.Save(stream, formaw);
- stream.Position = 0;
- return stream;
- } catch (Exception ex)
- {
- throw;
- }
- }
- }
- }
IService1.cs
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Runtime.Serialization;
- using System.ServiceModel;
- using System.ServiceModel.Web;
- using System.Text;
- using System.IO;
- using System.Drawing;
- using System.Drawing.Imaging;
- namespace PhotoService
- {
- [ServiceContract]
- public interface IService1
- {
- [OperationContract]
- [WebGet(UriTemplate = "/GetImages", RequestFormat = WebMessageFormat.Json,
- ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
- string[] GetImages();
- }
- }
Web Application to consume web service
Default.aspx
- <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
- <!DOCTYPE html>
- <html
- xmlns="http://www.w3.org/1999/xhtml">
- <head runat="server">
- <title></title>
- </head>
- <body>
- <form id="form1" runat="server">
- <div>
- <asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="Get Images from Base64 strings" />
- <br />
- <asp:Repeater ID="FileRepeater" runat="server">
- <ItemTemplate>
- <asp:Image ID="Image1" runat="server" ImageUrl="
- <%# Container.DataItem %>" />
- </ItemTemplate>
- </asp:Repeater>
- </div>
- </form>
- </body>
- </html>
Default.aspx.cs
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.UI;
- using System.Web.UI.WebControls;
- using System.Runtime.Serialization;
- using System.Net;
- using System.IO;
- using System.Xml.Linq;
- using System.Xml;
- using System.Runtime.Serialization.Json;
- public partial class _Default: System.Web.UI.Page
- {
- protected void Page_Load(object sender, EventArgs e) {}
- static int count = 0;
- protected void Button2_Click(object sender, EventArgs e)
- {
- try
- {
- HttpWebRequest request = WebRequest.Create("http://localhost:21269/Service1.svc/GetImages") as HttpWebRequest;
- using(HttpWebResponse response = request.GetResponse() as HttpWebResponse) {
- if (response.StatusCode != HttpStatusCode.OK) throw new Exception(String.Format("Server error (HTTP {0}: {1}).", response.StatusCode, response.StatusDescription));
- DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(string[]));
- object objResponse = jsonSerializer.ReadObject(response.GetResponseStream());
- string[] data = objResponse as string[];
- count = data.Length;
- System.Drawing.Image[] Converted_Image = new System.Drawing.Image[count];
- Converted_Image = Base64ToImage(data);
- for (int i = 0; i < count; i++)
- {
- string filename = Server.MapPath("~/Images/" + i + ".jpg");
- Converted_Image[i].Save(filename);
- }
- string[] list = Directory.GetFiles(Server.MapPath("~/Images"));
- var aList = from fileName in Directory.GetFiles(Server.MapPath("~/Images")) select string.Format("~/Images/{0}", Path.GetFileName(fileName));
- FileRepeater.DataSource = aList;
- FileRepeater.DataBind();
- }
- } catch (Exception ex)
- {
- Response.Write("Error : " + ex.Message);
- }
- }
- public System.Drawing.Image[] Base64ToImage(string[] base64String)
- {
- System.Drawing.Image[] image = new System.Drawing.Image[count];
- for (int i = 0; i < count; i++)
- {
- byte[] imageBytes = Convert.FromBase64String(base64String[i]);
- MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
- ms.Write(imageBytes, 0, imageBytes.Length);
- image[i] = System.Drawing.Image.FromStream(ms, true);
- }
- return image;
- }
- }