I'm using a database to store clients' images as bytes. How can I render these images on an .aspx page?
3 Answers
Two solutions.
Build a handler page. That takes an ImageID/RowID as GET parameter and returns data with mimetype image/jpeg or image/png.
Use DATA uri scheme as explained on wikipedia.
<img src="data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAABGdBTUEAALGP C/xhBQAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9YGARc5KB0XV+IA AAAddEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIFRoZSBHSU1Q72QlbgAAAF1J REFUGNO9zL0NglAAxPEfdLTs4BZM4DIO4C7OwQg2JoQ9LE1exdlYvBBeZ7jq ch9//q1uH4TLzw4d6+ErXMMcXuHWxId3KOETnnXXV6MJpcq2MLaI97CER3N0 vr4MkhoXe0rZigAAAABJRU5ErkJggg==" alt="Red dot" />

- 11,961
- 7
- 52
- 75
-
5Nice.. I'd never heard of the DATA uri sheme. +1 to you. That's why I love this site.. Something new every day... – David Aug 07 '10 at 16:17
-
@david - even I knew very late in my career. i had belief only file paths are allowed there. – ankitjaininfo Aug 07 '10 at 16:22
-
@ankit +1, ditto @David. Never heard of it; will solve a big, huge problem for me: pre-downloading png images. CSS classes that incorporate base-64-encoded images will (I think!) be much quicker, more reliable, and more repeatable than other well-known but imo somewhat ugly, hackish pre-downloading schemes. – Pete Wilson Aug 07 '10 at 17:37
-
@lcplben.. ooh ya. this is ugly as these images are never cached and travel with page content. Not good for bigger images. And do not use second method for the sake of PRE-LOADING images. – ankitjaininfo Aug 07 '10 at 17:44
-
@Ankit thanks for reply..is we have to use data:image/png;base64 for every image byte array? – BreakHead Aug 09 '10 at 06:36
-
here is what I am trying to System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding(); investorLogo.Src = string.Format("data:image/png;base64,{0}", enc.GetString(investor.Logo)); but its rendering all bytes – BreakHead Aug 09 '10 at 06:45
Instructions can be found here: http://www.dotnetcurry.com/ShowArticle.aspx?ID=129&AspxAutoDetectCookieSupport=1
in step 4, but the whole article is worth a read.

- 72,686
- 18
- 132
- 173
This can be done easily by converting the Byte Array to a Base64 image.
public string GetImageAsBase64String(byte[] bin)
{
if (bin != null)
{
return "<img src=\"data:image/jpeg;base64," + Convert.ToBase64String(bin) + "\">";
}
else
{
return null;
}
}
//usage, for demo purposes an uploaded image from a FileUpload Control
Label1.Text = GetImageAsBase64String(FileUpload1.FileBytes);

- 35,079
- 22
- 62
- 79