How can I dynamically resize an image in ASP.NET MVC?
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?
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.
You can definitely reuse the same IHttpHandler
. You just need a new IRouteHandler to map the incoming request to the correct handler:
public class ImageRouteHandler : IRouteHandler
{
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
return new YourImageHttphandler();
}
}
In your routes, add:
routes.Add("Images", new Route("images/{*file}", new ImageRouteHandler()));
Now any request in /images
(e.g. /images/pic.jpg?width=320&height=240
) will be handled by your existing handler. Obviously you can change the route pattern to match any path that makes sense, just like a typical MVC route.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With