Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC: loading images from database and displaying their in view

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.

like image 454
Kai Avatar asked Nov 10 '10 08:11

Kai


1 Answers

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.

like image 98
Darin Dimitrov Avatar answered Sep 20 '22 06:09

Darin Dimitrov