views:

67

answers:

1

I have saved an image on the database and want to display it to the user.

The table the image is stored in looks like this:

        Images
        ------
ImageData      Byte
ImageName      String
ContentType    String

What should I do to load and show it in my View?

+5  A: 

In Image controller class:

public ActionResult ProfileImage(string userName)
{
   var imageByteArray = // get image bytes from DB corresponding to userName
   string contentType = // get image content type from DB for example "image/jpg"
   string fileName = // get image file name from DB

   return File(imageByteArray, contentType, fileName);
}

In view:

<img src='/Image/ProfileImage/yourUserName' alt='Profile image' />

You'll also need a custom route in Global.asax:

routes.MapRoute(
   "ProfileImage",                                                    
   "Image/ProfileImage/{userName}",                           
   new { controller = "Image", action = "ProfileImage", userName = "" }
);

You can also load the image in Bitmap and apply changes like resizing, rotation and so on. If you do that consider saving the image as png since GDI+ (System.Drawing) can keep best quality and transparency with this format. It is also good practice to cache dynamic images.

Branislav Abadjimarinov
ImageData = Convert.ToByte[](reader["@ImageData"]);how can I read information of byte type? i have something wrong after first "]".
Ragims
what does it meen 15?? imageName?
Ragims
Sorry, it should be the user name (or image name if you decide so)
Branislav Abadjimarinov