Inline Image in ASP.NET
- by Ricardo Peres
Inline images is a technique that, instead of referring to an external URL, includes all of the image’s content in the HTML itself, in the form of a Base64-encoded string. It avoids a second browser request, at the cost of making the HTML page slightly heavier and not using cache. Not all browsers support it, but current versions of IE, Firefox and Chrome do. In order to use inline images, you must write the img element’s src attribute like this: 1: <img src="data:image/gif;base64,R0lGODlhEAAOALMAAOazToeHh0tLS/7LZv/0jvb29t/f3//Ub/
2: /ge8WSLf/rhf/3kdbW1mxsbP//mf///yH5BAAAAAAALAAAAAAQAA4AAARe8L1Ekyky67QZ1hLnjM5UUde0ECwLJoExKcpp
3: V0aCcGCmTIHEIUEqjgaORCMxIC6e0CcguWw6aFjsVMkkIr7g77ZKPJjPZqIyd7sJAgVGoEGv2xsBxqNgYPj/gAwXEQA7"
4: width="16" height="14" alt="embedded folder icon"/>
The syntax is: data:[<mediatype>][;base64],<data>
I developed a simple control that allows you to use inline images in your ASP.NET pages. Here it is:
1: public class InnerImage: Image
2: {
3: protected override void OnInit(EventArgs e)
4: {
5: String imagePath = this.Context.Server.MapPath(this.ImageUrl);
6: String extension = Path.GetExtension(imagePath).Substring(1);
7: Byte[] imageData = File.ReadAllBytes(imagePath);
8:
9: this.ImageUrl = String.Format("data:image/{0};base64,{1}", extension, Convert.ToBase64String(imageData));
10:
11: base.OnInit(e);
12: }
13: }
Simple, don’t you think?