0

Possible Duplicate:
How to show a image in database in the image control of Asp.net?

I am returning a list of products from a database. Inside this list i am saving database images as bytearrays. Currently I am displaying about 30 products on a page and i would like to add their images next to the product information. What would be the easiest way to go about this?

What I have:

public Image PopulatePicture()
{
    Image newImage;
    //Read image data into a memory stream
    using (MemoryStream ms = new MemoryStream(ImageByteArray, 0, ImageByteArray.Length))
    {
        ms.Write(ImageByteArray, 0, ImageByteArray.Length);

        //Set image variable value using memory stream.
        newImage = Image.FromStream(ms, true);
    }
    return newImage;
}

I have an error on Image.FromStream (System.Web.UI.WebControls does not contain a definition for FromStream)

Community
  • 1
  • 1
Troy Loberger
  • 347
  • 1
  • 8
  • 28

3 Answers3

2

If your using Mvc its rather simple

Simply write an action such as the following

public FileContentResult Image()
{
   //Get the Byte Array for your image
   byte[] image = FilesBLL.GetImage();

   //Return a jpg
   //Note the second parameter is the files mime type
   return File(image, "image/jpeg");
}

See This Link For Mime types

http://www.webmaster-toolkit.com/mime-types.shtml

I highly suggest adding a column to your files table to store mime types (determine this on upload)

And in your view put down an image like this

<img src='@Url.Action("GalleryMediumThumb")'/>

for webforms see

How to show a image in database in the image control of Asp.net?

Community
  • 1
  • 1
Ben Janecke
  • 157
  • 5
1

You likely have a few issues here:

  1. You are referencing an asp.net Image object (System.Web.UI.WebControls.Image) not the GDI+ System.Drawing.Image object that you want. Clarify your namespace.

  2. You can't dispose the stream on the image. Drop the using block. https://stackoverflow.com/a/13696705/64262

  3. You will need to write the resulting stream to the response stream (negating the need to convert it to an image in the first place), and then reference that endpoint from an <img> tag.

Community
  • 1
  • 1
andleer
  • 22,388
  • 8
  • 62
  • 82
0

A generic ASP.NET Handler (*.ashx) could load the image from the database and stream it as a normal image to the browser.

May this http://coffeedrivendevelopment.net/2012/10/26/sharing-image-resources-between-wpf-and-asp-net/ will help you. It is about images in ressources, but the way is the same.

Kai
  • 1,953
  • 2
  • 13
  • 18