javisrk
javisrk

Reputation: 582

How to efficiently serve images in ASP.NET MVC

In Razor I have a loop that gives me results. In that loop, I have a Url.Action that serves an image:

foreach (var i in Model.InventoryList)
        {
        <tr>                
            <td style="text-align: center;"><img alt="@i.ProductCode" src="@Url.Action("GetImageThumbnail", "ServiceRequest", new { ProductCode = i.ProductCode })" onclick="showGallery('@i.ProductCode');" /></td>                
        </tr>
        }

The image served is dependent on if the image for that particular row exists. If it doesn't, an alternate image is served.

public ActionResult GetImageThumbnail(string productCode)
    {            
        string filePath = "path_to_product.png";
        Size size = new Size(80, 50);
        if (!System.IO.File.Exists(filePath))
        {
            filePath = "No_image_available.png";
            size = new Size(50, 50);
        }
        using (MemoryStream ms = new MemoryStream()){
            Image image = Image.FromFile(filePath);
            image = ImageHelpers.ResizeImage(image, size);
            image.Save(ms, ImageHelpers.getImageFormat(filePath));
            return File(ms.ToArray(), ImageHelpers.getContentType(filePath));
        }

    }

Now this is fine, and works pretty fast if there are a few results. If there are thousands of results, there is some definite slowdown in serving all those instances of images. Is there a more efficient way of doing this?

I could be serving less results in the model but that's not what I'm aiming for in this particular question.

Upvotes: 3

Views: 2036

Answers (1)

ramiramilu
ramiramilu

Reputation: 17182

Some options I would say -

  • You can DiskCache Plugin of IIS for resized images. Instead of making all the resizing calculations on the fly, save the resized image at the time of image creation itself. Later if you do not want resized image, it can be deleted at any point of time.
  • Some other plugins like SourceMemCache, OutputMemCache and SourceDiskCache also available for IIS in DiskCache plugin itself.
  • Alternatively, you can write all the resized images to cache providers like Redis.io or to Squid
  • Lazy Load images on your page
  • Try to redesign your page, I mean even if it is a gallery page, try to use pagination, so that thousands of images in a gallery will boil down to few tens on a single page.

Upvotes: 2

Related Questions