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.
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
IE9 seems to have this fixed http://blogs.msdn.com/b/ieinternals/archive/2010/09/15/ie9-beta-minor-change-list.aspx
i’m testing wiht IE9 but the application force the ie7 compability…maybe is that..
Thanks..
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
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 š
I have been looking for information about this for a while and this article is the most accurate, thank you and keep it up!