Umbraco image library and SVG images

In previous versions of the CMS core, all links to images have been stored as a single text string which would mean that developers wouldn’t have to check for a type of media image that was consumed on an Umbraco page.

With the introduction of the image cropper type, the way in which images are stored in umbraco have changed.

There are two ways in which images are stored in the cmsPropertyData table
With no focus points

{ "src": "", crops: [] }

With focus points

{ "focalPoint": { "left": 0.5, "top": 0.5 }, "src": "" }

If you look in the cmsPropertyType table, this should effect types Upload image (6) and Thumbnail Image (135)

In your umbraco project, you would use the following code to extract the new image.

UmbracoHelper umbracoHelper = new Umbraco.Web.UmbracoHelper(Umbraco.Web.UmbracoContext.Current);
var mediaItem = umbracoHelper.Media(content.GetPropertyValue(fieldName));
Var imageSrc = mediaItem.umbracoFile.src

This works fine as long as you are not consuming any media item that falls under the .jpg, .png, .gif. Umbraco detects the SVG format as a file type and sets the cmsPropertyData Upload file(24) to a physical URL of the file that needs to be used.

This now depending on how you serve your images to your templates. I use an extension method for the IPublishedContent and a fieldName, which I can call in my views.

Here I need to check the type of object that is being brought back via the IPublishedContent. The new image cropper images will return an object of Umbraco.Web.Models.ImageCropDataSet and an SVG will return a string.
Calling the src field name on an mediaItem.umbracoFile when returning an SVG will throw an exception.

I have chosen to check the type of what is being returned. Check out this great post to get a good example of looking up a type in a switch that doesnt use heavy reflection.

We have added the following code to the extension method.

var ts = new TypeSwitch()
    .Case((Umbraco.Web.Models.ImageCropDataSet x) => result = mediaItem.umbracoFile.src)
   .Case((string x) => result = mediaItem.umbracoFile);


We can now pick either an SVG or an image from the media library, it wont throw an exception as you will be returning either the src of the image cropper object, or the URL of the uploaded file type.

2 thoughts on “Umbraco image library and SVG images

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s