Embedding Images in HTML using C#

In HTML pages, images are typically linked rather than embedded using the

<img src="[protocol]://[url]" />

tag. If you want to embed the image data, for example to handle just a single file containing text and images, you need to replace the src attribute with the Base64-encoded binary content of the image using the data: protocol:

<img src="data:image/jpeg;base64,[data]">

To encode an image file in Base64, use the following function (originally found here):

string MakeImageSrcData(string filename)
{
  FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
  byte[] filebytes = new byte[fs.Length];
  fs.Read(filebytes, 0, Convert.ToInt32(fs.Length));
  return "data:image/png;base64," +
    Convert.ToBase64String(filebytes, Base64FormattingOptions.None);
}

This function can now be used to render an image in either aspx/ascx:

<img src="<%=MakeImageSrcData("c:\path\to\my.png") %>" />

or C#

Response.Output.WriteLine("<img src=\"" + 
    MakeImageSrcData("c:\path\to\my.png") + "\"/>");

The rendering result depends on the browser, though, as Wikipedia describes:

  • Firefox and Chrome render the embedded images correctly
  • Internet Explorer (7 (Vista)/8 (Win7)) only renders some because of a 32kB limit
  • Word 2007 only renders image placeholders

This is too bad, since I originally intended to generate WordHtml and include pictures directly in HTML.

6 thoughts on “Embedding Images in HTML using C#

  1. Hi, great post. I’m having with the “Internet Explorer (7 (Vista)/8 (Win7)) only renders some because of a 32kB limit”.
    Do you know if exists a workaround for that?
    Thanks

  2. Hi Everyone. I am getting problem with word document . Image is not showing when i generate word document using html and c#. It shows but if i will remove image from its path. Then image in word document not showing. Plz help me if you can. Its urgent.

    Thanks in Advance

    Regards
    Avneesh Pandey

  3. I’ve been looking for a way to do this for a couple of days now (on top of other things!), the problem I initially had was not being able to get to the photo’s on my c: , but using this worked immediately.

    Thanks so much, very impressive šŸ™‚

  4. I have been looking for information about this for a while and this article is the most accurate, thank you and keep it up!

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.