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?

0

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.