How to get Sitecore Media image URL in Code

In many scenarios, we would require Sitecore Image Item absolute URL to bind into the carousel, repeater or any other image component. We may need to read the Image Field in the Sitecore item and get the URL of the particular image. There are few extra lines of code that needs to be written in order to get Sitecore Media image URL in Code behind.

Recommended Articles

How to get Sitecore Media image URL in Code

The following snippet will help you get media URL from Sitecore Image Field. We need to get image url from media library using MediaManager.GetMediaUrl() Method.

public static string GetImageURL(Item currentItem)
{
          string imageURL = string.Empty;
          Sitecore.Data.Fields.ImageField imageField = currentItem.Fields["Image"];
          if (imageField != null && imageField.MediaItem != null)
          {
            Sitecore.Data.Items.MediaItem image = new Sitecore.Data.Items.MediaItem(imageField.MediaItem);
            imageURL = Sitecore.StringUtil.EnsurePrefix('/', Sitecore.Resources.Media.MediaManager.GetMediaUrl(image));
          }
return imageURL;
}

The above code is very simple and straight forward. In the current item, the Image field is extracted and stored into a Sitecore ImageField variable and with the help of media item, we can read the Media URL using MediaManager.GetMediaURL(image) method.

Leave a Reply

Your email address will not be published.

Sign Up for Our Newsletters

Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.

You May Also Like