r.r
r.r

Reputation: 7153

How do I load an image from a database in ASP.NET MVC?

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?

Upvotes: 1

Views: 294

Answers (1)

Branislav Abadjimarinov
Branislav Abadjimarinov

Reputation: 5131

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.

Upvotes: 6

Related Questions