Friday, May 18, 2012

How to embed image into HTML document?


In this blog post, I will demonstrate how to embed image into HTML document.

Usually we provide image path to the src attribute of image tag.
<img src=” C:\SamplePictures\lighthouse.png” />

However there will be circumstances in web applications where you want to provide the HTML as downloadable content to the user. In such circumstances if the HTML document contains any external resources like Images, CSS etc., they will not be referenced/preserved along with the downloaded HTML document Hence the end user may not be viewing the appropriate document.

To achieve the integrity of the HTML document, external resources like images, CSS can be embedded into the document. This can be achieved in 2 steps.

Step 1: Create Base64 representation of Image
string base64 = Convert.ToBase64String(imageBytes); //This will convert the image bytes into base64 string.

Step 2: In the src attribute of image tag, provide image information in below format.
Format:
data:[<MIME-type>][;charset=<encoding>][;base64],<data>

ex:
<img src="data:image/png;base64,iVBsafd .. .. ..”/>

Now open the document in browser, we can view the embedded image.

Data URI scheme:
Data URI scheme is a URI scheme that provides a way to include data in-line with web pages as if they were external resources. This allows images and style sheets to be fetched in single HTTP request rather than multiple HTTP request.

Browser support:
All major browsers like Firefox, Safari, Android, Chrome, IE8 and IE9 provide support for this data URI scheme.

Sample C# code snippet:
FileStream fs = new FileStream(<<ImagePath>>, FileMode.Open, FileAccess.Read);
byte[] imageBytes = new byte[fs.Length];
fs.Read(imageBytes, 0, imageBytes.Length);
StreamWriter streamWriter = new StreamWriter("test.html");
streamWriter.WriteLine("<html>");
streamWriter.WriteLine("<title>EmbeddingImage</title>");
streamWriter.WriteLine("<body>");
streamWriter.Write("<img src=\"data:image/"+ <<FileExtension>>
+ ";base64," + Convert.ToBase64String(imageBytes) + "\"/>");
streamWriter.WriteLine("</body>");
streamWriter.WriteLine("</html>");
streamWriter.Close();
System.Diagnostics.Process.Start("test.html");

For more information on this refer below links:

2 comments:

  1. Hi Rajendran,

    Nice Article!!!!!

    Can you please look the Sprite and Image Optimization framework? it is advanced method to embed the image into html/css.

    http://aspnet.codeplex.com/releases/view/65787

    http://weblogs.asp.net/craigshoemaker/archive/2010/08/06/asp-net-sprite-amp-image-optimization-framework-intro-in-webforms.aspx

    Regards,
    M. Balaji

    ReplyDelete
  2. Hi Balaji,

    Thanks for the feedback and the valuable information.

    Regards
    Rajendran

    ReplyDelete