In a previous post, I explained how you can use the DD4T.Web library to serve binary files (like images, documents, etc) directly from the broker database. This was done with the BinaryDistributionModule.
There is an additional benefit to reap from this: the BinaryDistributionModule is able to resize your images on the fly. Here’s how.
Let’s say that you have a JPG image published to the broker database, with the URL /images/ouroffice_tcm3-4954.jpg. If you use a browser to request this image, the binary data is extracted from the broker database by the module, and stored on the file system. You should see something like this:
Now when you request the URL /images/ouroffice_tcm3-4954_w150.jpg, this is what you get:
You may be thinking “that’s easy, they simply uploaded a smaller version into Tridion”. But a look at the URL reveals that this cannot be the case: the URI (the ‘3-4954’ bit) is the same, which means that there is only one image in the CMS. Actually, all that’s different between those URLs is the string “_w150” at the end of the filename, right before the file extension.
Substitute for variants
The traditional approach to having thumbnail versions of images is by creating a variant in your template code. But that doesn’t make much sense with DD4T. An implementation using this framework hardly touches Tridion templates at all, and instead focuses completely on the web application. Hence it made sense to implement ‘thumbnailing’ on the web application side as well.
So how does this work in a Razor view? Let’s first look at the typical way to display an image:
<img src="@Model.Fields["image"].LinkedComponentValues.Multimedia.Url" />
The Multimedia.Url property contains the (local) url of the image you’re trying to show, e.g. /images/ouroffice_tcm3-4954.jpg. Somehow we need to insert this ‘_w150’ string into this. Fortunately DD4T offers a helper method which comes to the rescue:
<img src="@Model.Fields["image"].LinkedComponentValues.Multimedia.Url.ResizeToWidth(150)" />
When this snippet is requested by the browser, it looks like this:
<img src=" /images/ouroffice_tcm3-4954_w150.jpg" />
Besides ResizeToWidth there is also a ResizeToHeight and even ResizeToWidthAndHeight, which takes two integers as parameters.