2

I am trying to display the images in my Asp.Net MVC 1.0 application.

I can successfully get the Image (into byte[]) from DB.

How can I display it into the <img>?

1
  • at least try to post sufficient info. for someone to be able to answer. Commented Jul 12, 2009 at 6:24

3 Answers 3

5

Return a FileResult from action method:

return File(imageData, "image/png"); 

Note that outputting HTML of the page and the image should be done in two separate requests. You have to generate a URL for the src attribute to the action that returns the image and in that action, you can output the image contents.

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

2 Comments

I am already using this, below is my action in ImageController public ActionResult ShowImage(int id) { byte[] image=GetImage(id); return File(image,"image/jpg"); } and in my HTML page I am using Html.Image helper <%= Html.Image(Url.Action("ShowImage","Image",new{id=ViewData["ID"]}))%> but when I tried it.. my Url.Action("ShowImage","Image",new{id=ViewData["ID"]}) ==null so this is the error: Value cannot be null or empty. Parameter name: imageRelativeUrl any Ideas? Kind Regards, Saurabh
@saurabh: Why don't you add all that code from your comment to your question as a clarification what you've been doing but is not working. It will be formatted and people won't have to read all the comments to get additional info about your problem.
2

This works (tested):

<img src="<%= Url.Action("ShowImage", "Image", new { Id = imageId }) %>" />

1 Comment

I am doing this and I cannot get it to work in Chrome nor Safari
-4

SQL is not a good place to store images

Says Microsoft, and they have every reason to back SQL. It's fast on your development machine, but it doesn't scale.

It's better to store image paths in SQL instead, and store the image files themselves on the filesystem.

If you already have images in your DB and can't migrate, disk caching can eliminate the overhead.

DISCLAIMER: I'm the author of this software

The free ImageResizing.Net library has an (AGPL/commercial) SqlReader plugin, which supports any database schema, and can serve images from SQL as efficiently as is possible. Add the disk caching plugin, and you'll be back to filesystem-level performance and scalability with minimal development effort.

2 Comments

the user has asked about how to show images, he didnt ask if its a good practice or not.
My answer covered that as well, although it wasn't the focus of my answer. Disk caching is very important if you're passing byte[] arrays from SQL to the server, and as Merhdad's answer has already shown the simple way to do it, I'm adding value to this topic by explaining why it's a bad idea, and how to make aforementioned bad idea have a less drastic impact on server performance and stability.

Your Answer

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