May 29, 2014

In the previous post, I showed how to save an image to a database. In this post, I will show how to retrieve an image and display it in an asp.net page. Note that the image is saved in bytes format rather than as a file and displaying it in an asp.net Image control requires more work. Therefore, in this post, I have used the html img element to display the image.

Here is how the front end looks like.

front end
  1. <asp:Button ID="b2" runat="server" Text="show img" OnClick="b2_Click" />
  2. <%--<asp:Image ID="Im1" runat="server" />--%>
  3. <img id="im1" runat="server" />


In the backend, I have used a fixed id for retrieving the image from the database. You will need to modify the front end to get the required id. I have a method "GetImage" that retrieves necessary data from the database and gets the image as bytes. In the button click event that displays the image, the source of the image is set by setting image type and adding the bytes as Base64 string.

retrieve &amp; show image
  1. protected void b2_Click(object sender, EventArgs e)
  2. {
  3.     //used a fixed id for getting image
  4.     //modify front end to retrieve the req id.
  5.     int id = 1;
  6.     string srcUrl = string.Empty;
  7.  
  8.     ImgPrac im = GetImage(id);
  9.     
  10.     //the following can be improved by adding a
  11.     //new method to get image types
  12.     if (im.Name.ToLower().EndsWith(".jpg"))
  13.         srcUrl = "data:image/jpg;base64,";
  14.     else if (im.Name.ToLower().EndsWith(".png"))
  15.         srcUrl = "data:image/png;base64,";
  16.  
  17.     im1.Src = srcUrl + Convert.ToBase64String(im.Photo);
  18. }
  19.  
  20.  
  21. private ImgPrac GetImage(int id)
  22. {
  23.     byte[] fileBytes = null;
  24.  
  25.     ImgPracEntities en = new ImgPracEntities();
  26.     ImgPrac im = en.ImgPracs.FirstOrDefault(c => c.Id == id);
  27.  
  28.     if (im != null)
  29.         fileBytes = im.Photo;
  30.  
  31.     return im;
  32. }

0 comments:

Reference: Shahed Kazi at AspNetify.com