With ImageGen for Umbraco you can automatically resize and cache images server side. I presume you already know ImageGen, why this guide won’t dig more into the concepts and functionality here for.
Instead I’ll show you how to make a Razor Helper, with a helper method which returns a processed image.
A Razor Helper is a helper class with methods you can use across your Razor Views.
1. Create a new .cshtml class and place it in /App_Code
2. Reference the following assemblies
[csharp]
@using System.Web.Mvc
@using umbraco.MacroEngines
[/csharp]
3. Create the following helper method
[csharp]
@helper ImageGenNiceUrl(DynamicNode imageNode, int width, int height)
{
//Get image with ImageGen and return just the URL with set width/height
if (imageNode != null)
{
@MvcHtmlString.Create(String.Format("{0}{1}{2}{3}{4}{5}", "/ImageGen.ashx?image=", imageNode.NiceUrl, "&width=", width, "&height=", height))
}
}
[/csharp]
The method takes the parameters DynamicNode, width and height, and returns the image url as a string.
I assume you have ImageGen installed and placed ImageGen.ashx in the root of your website, otherwise change the first parameter in String.Format to the appropriate.
We need to use MvcHtmlString.Create, otherwise “&” will be returned as: [html]&[/html] and ImageGen won’t recognize the parameters.
ImageGen supports several other parameters, so you can extend the method as desired. This is just to show you the basics.
Our helper method is now done, and we can use it in our Razor Views.
4. Example:
[csharp]
<img src="@LayoutHelper.ImageGenNiceUrl(currentNode.Media("imagePicker"), 128, 256)" />
[/csharp]
currentNode reflects a DynamicNode, which contains a image picker with the property name “imagePicker”.
128 (width), 256 (height) is the proportions we want our image to be.
If you provide width and height with 0 value for both parameters, the image won’t be scaled. Providing 0 for just one of the parameters, will scale the opposite parameter.
You can choose to include [html]<img></img>[/html] in your helper, but I prefer it this way, as it makes it very easy to extend with eg. class, data or other properties.
If you want to read more about Razor Helpers, check out this post by Scott Gu.