## 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];
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 Responses to Embedding Images in HTML using C#

1. marcos alves says:

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. marcos alves says:

i’m testing wiht IE9 but the application force the ie7 compability…maybe is that..

Thanks..

3. 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.