How can I dynamically resize an image in ASP.NET MVC?

Daniel T. picture Daniel T. · Sep 11, 2009 · Viewed 16.7k times · Source

Question

How can I dynamically resize an image in ASP.NET MVC?

Background

I'm trying to automatically create thumbnails from images that are already on the server. In ASP.NET Webforms, I created a HTTPHandler to do this and added verbs in the web.config for all image extensions to pass through the handler. The handler was nice in that if you wanted the original image, you'd use a typical image tag:

<img src="pic.jpg"/>

But if you wanted a resized image, you'd use:

<img src="pic.jpg?width=320&height=240"/>

Is there a way to duplicate the same behavior in ASP.NET MVC?

Answer

Leniel Maccaferri picture Leniel Maccaferri · Apr 26, 2012

Using WebImage class that comes in System.Web.Helpers.WebImage you can achieve this.

You can use this great kid to output resized images on the fly.

Sample code:

public void GetPhotoThumbnail(int realtyId, int width, int height)
{
    // Loading photos’ info from database for specific Realty...
    var photos = DocumentSession.Query<File>().Where(f => f.RealtyId == realtyId);

    if (photos.Any())
    {
        var photo = photos.First();

        new WebImage(photo.Path)
            .Resize(width, height, false, true) // Resizing the image to 100x100 px on the fly...
            .Crop(1, 1) // Cropping it to remove 1px border at top and left sides (bug in WebImage)
            .Write();
    }

    // Loading a default photo for realties that don't have a Photo
        new WebImage(HostingEnvironment.MapPath(@"~/Content/images/no-photo100x100.png")).Write();
}

In a view you'd have something like this:

<img src="@Url.Action("GetPhotoThumbnail",
     new { realtyId = item.Id, width = 100, height = 100 })" />

More about it here: Resize image on the fly with ASP.NET MVC

There's also a great tutorial on the ASP.NET site: Working with Images in an ASP.NET Web Pages (Razor) Site.