DEV Community

Alex Dhaenens
Alex Dhaenens

Posted on

How to resize images from the media library with code

One of the missions of a web developer is to make your sites fast & user friendly, something that can be measured by google's speed insights score. One way to do increase your score and speed is to download images in the right size instead of the ( -most of the time- way) bigger size just to then resize it using css. This obviously gives a better speed since you need to download alot less data (which is critical on mobile and low internet devices). In order to download the right size, content editors could upload the correct one to the media library. However this is, due to many reasons (e.g. reusing old images,...), not always possible.

Luckely for us, Sitecore does have this feature built in. You can resize image from the media library to any size by adding query parameters to the image's url and then adding a protective hash.

You can do this as follows in vanilla Sitecore:

string url = Sitecore.Resources.Media.MediaManager.GetMediaUrl(mediaItem);
string resizedImageSrc = HashingUtils.ProtectAssetUrl(url + $"?w={width}&h={height}")

For those of you that do use Glassmapper you can do it as follows:

string url = image.Src
string resizedImageSrc = HashingUtils.ProtectAssetUrl(url + $"?w={width}&h={height}")

Parameters

Besides from setting the width & height you can also set other query parameters:

° w: Width in pixels
° h: Height in pixels
° mw: Maximum width in pixels
° mh: Maximum height in pixels
° la: Language (defaults to context language)
° vs: Version (defaults to latest version)
° db: Database name (defaults to context database)
° bc: Background color (defaults to black, for white bc=ffffff)
° as: Allow stretch (as=1)
° sc: Scale by floating point number (sc=.25 = 25%)
° thn: Thumbnail (thn=1)
° dmc: Disable media caching, both retrieval and storage (dmc=1)

which you can just add to the query parameters.

Sources

https://community.sitecore.net/technical_blogs/b/sitecorejohn_blog/posts/media-options-and-query-string-parameters-in-the-sitecore-asp-net-cms

Discussion (0)