Rendering images

Works with version 3.0.3+

When inserting images into the page you will want to control the size of the image using Sitecore's ability to automatically resize images, this can all be handled through Glass.Mapper.

For this tutorial we will be using the following model, notice that the FeaturedImage property as the return type Glass.Mapper.Sc.Fields.Image:

    [SitecoreType(AutoMap = true)]
    public class NewsArticle : ContentBase
    {
        [SitecoreField]
        public virtual string Abstract { get; set; }

        [SitecoreField]
        public virtual string MainBody { get; set; }

        [SitecoreField]
        public virtual Image FeaturedImage { get; set; }

        [SitecoreField]
        public virtual DateTime Date { get; set; }
    }

Rendering an image is very straight forward using the GlassHtml helper methods:

    <%= GlassHtml.RenderImage(Model, x => x.FeaturedImage) %>

When rendered this will output the following HTML:

    <img src="/~/media/Site/catonsofa.ashx" alt="Cat on sofa" />

Sometimes we want to control the size of the image, we can do this by passing in a second set of parameters in the form of am anonymous type:

    <%= GlassHtml.RenderImage(news, x => x.FeaturedImage, new { W = 80, H = 80, Width = 80, Height = 80}) %>

This will output the following HTML, notice the additional parameters added to the image URL:

    <img src="/~/media/Site/catonsofa.ashx?w=80&h=50" width="80" height="50" alt="Cat on sofa">

You can get a complete list of the parameters support from Brian Pedersen blog.

The final step is to make the image work with the page editor by setting the final parameter to true.

     <%= GlassHtml.RenderImage(news, x => x.FeaturedImage, new { W = 80, H = 80, Width = 80, Height = 80}, true) %>