Thursday, October 30, 2014

Sitecore get the URL of an image stored in the media library

When a template uses the image field, any images the user references (and uploads) go into the Sitecore media library. This can of course be rendered using the sitecore control, however for more custom implementations and MVC projects, the image URL itself is enough. The following method takes in an object of type ImageField and outputs a string with the URL to this image.
/// <summary>
/// get image url from sitecore imagefield
/// </summary>
/// <param name="field">imagefield</param>
/// <returns>image url</returns>
public static string GetImageURL(ImageField field)
    string imageURL = string.Empty;
    if (field != null && field.MediaItem != null)
        Sitecore.Data.Items.MediaItem image = new Sitecore.Data.Items.MediaItem(field.MediaItem);
        imageURL = Sitecore.Resources.Media.MediaManager.GetMediaUrl(image);
    return imageURL;
If the image is not rendering and your site is set-up to replace any spaces in URLs with dashes, then please see Sitecore media (images) not rendering.


  1. Where in Sitecore should this code go?

    1. In your visual studio solution, if you have a common class with generic methods. Then you can call it from any code behind on any sublayouts. Alternatively you could place it in the code behind of the sublayout that would be accessing the image URL.