How to show a image in database in the image control of Asp.net? We have to show the image of employee along with his details in the asp.net page, but the issue is how to show the image on the asp.net image control for the image control takes picture by the property ImageUrl.
Kindly guide….
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You can create an HttpHandler(ashx) page which would take a querystring and set that as the imageUrl property of the image control
<asp:image id="imgEmployee" imageUrl="DisplayImage.ashx?employeeId=<someId>"/>
Now in DisplayImage.ashx, you can override the Processrequest like below:-
public void ProcessRequest (HttpContext context)
{
int employeeId;
if (context.Request.QueryString["employeeId"] != null)
employeeId = Convert.ToInt32(context.Request.QueryString["employeeId"]);
else
throw new ArgumentException("No parameter specified");
byte[] imageData= ;// get the image data from the database using the employeeId Querystring
Response.ContentType = "image/jpeg"; // You can retrieve this also from the database
Response.BinaryWrite(imageData);
}
Web.config changes:-
<httpHandlers> <add verb="*" path="img/*" type="DisplayImage"/> </httpHandlers>
Hope this helps..
Method 2
This can also be done without creating a handler.
//get the image from the database as byte array byte[] image = (byte[])dr["image"]; //set the ImageUrl of the Image Control as a Base64 string Image1.ImageUrl = "data:image/jpeg;base64," + Convert.ToBase64String(image)
Or if you want the with and height also, create an Image by using a MemoryStream and get the image properties.
using (MemoryStream ms = new MemoryStream(image))
{
System.Drawing.Image imageFromDB = System.Drawing.Image.FromStream(ms);
Image1.ImageUrl = "data:image/jpeg;base64," + Convert.ToBase64String(image);
Image1.Width = imageFromDB.Width;
Image1.Height = imageFromDB.Height;
}
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0