10

We have some images in our database and want to display their in view. I find two way to do this - the first: we create action method in controller that get an image from database and return FileContentResult:

public ActionResult GetImage( int id )
    {
        var imageData = ...get bytes from database...

        return File( imageData, "image/jpg" );
    }

code in view:

<img src='<%= Url.Action( "GetImage", "image", new { id = ViewData["imageID"] } ) %>' />

The second way is to use HttpHandler:

public void ProcessRequest(HttpContext Context)
  {
      byte [] b = your image...;
      Context.Response.ContentType = "image/jpeg";
      Context.Response.BinaryWrite(b);
  }

and code in view:

<img src="AlbumArt.ashx?imageId=1" />

The first question is what is the most efficient(work more faster) way to implement this functionality (and why it work faster)?
And the second question - is there is a way to put image in our view directly, when we first call action method to return this view? I mean that in action method we get list of images from database and pass their in view as list, and in view use this code:

<%=Html.Image(Model[i])%>

that code must put image into view directly from model.

2
  • Do you consider to put images files outside the db? Commented Nov 10, 2010 at 11:57
  • Yes, I placed most of the images in the file system, but I was interested in the solution described above. Commented Nov 10, 2010 at 13:04

1 Answer 1

6

There won't be much difference in performance between the two methods. Obviously using an http handler will be the fastest you could get because the request doesn't go through the MVC lifecycle (routing, instantiating a controller, model binding, invoking the action) but I think this is a micro optimization and I would personally use the first approach as it is more adapted in an MVC scenario. If you later realize that this is a bottleneck for your application by performing extensive load tests you could always switch to the http handler approach.

As far as your second question is concerned about the helper, the answer is no, you cannot do this easily. The only possibility is to use the data URI scheme but this is not supported by all browsers. This way if your model has the byte array of the image you could write a helper which renders the following:

<img src="data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAA..." alt="Red dot" />

The image data is base64 encoded directly into the page. Another drawback is that those images will never be cached and your HTML pages could become very large.

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

Comments

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.