Effortlessly resize images in Orchard 1.7

I’ve written several times about image resizing in .NET, but never in the context of Orchard. With the imminent release of Orchard 1.7, it’s time to correct this. The new version comes with an extensible media pipeline that enables you to define complex image processing workflows that can automatically resize, change formats or apply watermarks. This is not the subject of this post however. What I want to show here is one of the underlying APIs that enable that feature, and that comes in the form of a new shape.

Once you have enabled the media processing feature, a new ResizeMediaUrl shape becomes available from your views. All you have to do is feed it a virtual path and size (and, if you need to override defaults, a few other optional parameters), and it will do all the work for you of creating a unique URL for the resized image, and write that image to disk the first time the shape is rendered:

<img src="@Display.ResizeMediaUrl(Path: img, Width: 59)"/>

Notice how I only specified a maximum width. The height could of course be specified, but in this case will be automatically determined so that the aspect ratio is preserved.

The second time the shape is rendered, the shape will notice that the resized file already exists on disk, and it will serve that directly, so caching is handled automatically and the image can be served almost as fast as the original static one, because it is also a static image. Only the URL generation and checking for the file existence takes time.

Here is what the generated thumbnails look like on disk:The resized images on disk

In the case of those product images, the product page will download 12kB worth of images instead of 1.87MB. The full size images will only be downloaded as needed, if the user clicks on one of the thumbnails to get the full-scale.

This is an extremely useful tool to use in your themes to easily render images of the exact right size and thus limit your bandwidth consumption. Mobile users will thank you for that.

3 Comments

  • Can you explain how image resizing is intended to be used in content? Eg when writing a blog, how should images be inserted and sized?

  • @Dave: this is for theme developers, not content editors. For content editors, the new media picker offers image resizing as part of the Image Editing feature, but that is not the topic of this post.

  • WOW! This is incredible and SO easy to use. I see an update to the Avatars module soon after the 1.7 release (hint to Piotr) =)

    I designed a theme for a drummer running on Orchard. He's constantly uploading new photos from shows and this will make displaying them so much easier. No more resizing before upload!

Comments have been disabled for this content.