Reputation: 401
I retrieve image from database and want to display in an control.
The code:
MemoryStream str= new MemoryStream();
byte[] n = (byte[])db.imagefile;
str.Write(n, 0, db.imagefile.Length);
How can I bind a MemoryStream to an image control, without using a handler?
Upvotes: 0
Views: 2594
Reputation: 62301
You already have byte array from database, so you just need to convert byte array to Base64 encoded string.
Then assign the Base64 encoded string to ImageUrl of asp:Image control.
public class Database
{
public byte[] Imagefile { get; set; }
public Database()
{
// PNG Red dot
Imagefile = new byte[]
{
137,80,78,71,13,10,26,10,0,0,0,13,73,72,
68,82,0,0,0,10,0,0,0,10,8,6,0,0,0,141,50,
207,189,0,0,0,4,103,65,77,65,0,0,177,143,
11,252,97,5,0,0,0,9,112,72,89,115,0,0,11,
19,0,0,11,19,1,0,154,156,24,0,0,0,7,116,
73,77,69,7,214,6,1,23,57,40,29,23,87,226,0,
0,0,29,116,69,88,116,67,111,109,109,101,110,
116,0,67,114,101,97,116,101,100,32,119,105,
116,104,32,84,104,101,32,71,73,77,80,239,100,
37,110,0,0,0,93,73,68,65,84,24,211,189,204,
189,13,130,80,0,196,241,31,116,180,236,224,
22,76,224,50,14,224,46,206,193,8,54,38,132,
61,44,77,94,197,217,88,188,16,94,103,184,234,114,
31,127,254,173,110,31,132,203,207,14,29,235,
225,43,92,195,28,94,225,214,196,135,119,40,
225,19,158,117,215,87,163,9,165,202,182,48,
182,136,247,176,132,71,115,116,190,190,12,
146,26,23,123,74,217,138,0,0,0,0,73,69,78,
68,174,66,6,130
};
}
}
protected void Page_Load(object sender, EventArgs e)
{
var db = new Database();
Image1.ImageUrl = string.Concat("data:image/png;base64,",
Convert.ToBase64String(db.Imagefile));
}
As of March 2012, Data URIs are supported by the following web browsers:
Trident
Internet Explorer 8: Microsoft has limited its support to certain "non-navigable" content for security reasons, including concerns that JavaScript embedded in a data URI may not be interpretable by script filters such as those used by web-based email clients. Data URIs must be smaller than 32 KB in Version 8.[3] Data URIs are supported only for the following elements and/or attributes:
Internet Explorer 9: Internet Explorer 9 does not have 32KB limitation and supports more elements.
http://en.wikipedia.org/wiki/Data_URI_scheme#Web_browser_support
Upvotes: 1