How To Get A Sitecore Image Url In Code

This is such a simple question I thought that it would have been written about somewhere else (but I couldn’t see can’t find a clear answer)…. How do I get the Url of a Sitecore image field in code. To get the Url from an Image field in Sitecore via code, you can use the following snippet:

using Sitecore;
using Sitecore.Data.Items;
using Sitecore.Resources.Media;
public string GetUrl()
{
var currentItem = Sitecore.Context.Item;
var imageUrl = string.Empty;
Sitecore.Data.Fields.ImageField imageField = currentItem.Fields["Image"];
if (imageField?.MediaItem != null)
{
var image = new MediaItem(imageField.MediaItem);
imageUrl = StringUtil.EnsurePrefix('/', MediaManager.GetMediaUrl(image));
}
}

Jon D Jones

Software Architect, Programmer and Technologist Jon Jones is founder and CEO of London-based tech firm Digital Prompt. He has been working in the field for nearly a decade, specializing in new technologies and technical solution research in the web business. A passionate blogger by heart , speaker & consultant from England.. always on the hunt for the next challenge

More Posts

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *