Access image fields
You can use the Sitecore.Data.Fields.ImageField
class to access data template fields of type Image. You can use the Sitecore.Data.Fields.ImageField.MediaItem
property to access the media item selected in the field as a Sitecore.Data.Items.Item
. If the field does not specify an image, then the Sitecore.Data.Fields.ImageField.MediaItem
property is Null.
You can use the Sitecore.Resources.ImageBuilder
class to construct an HTML <img>
element. You can use the Sitecore.Resources.Media.MediaManager.GetMediaUrl
method to determine the URL of a media item. For example, to construct an HTML <img> element based on the value of the Image field named ImageField
in the /Sitecore/Content/Home item in the Master database:
Sitecore.Data.Database master = Sitecore.Configuration.Factory.GetDatabase("master");
Sitecore.Data.Items.Item home = master.GetItem("/sitecore/content/home");
Sitecore.Data.Fields.ImageField imageField = home.Fields["imagefield"];
if (imageField!=null && imageField.MediaItem!=null)
{
Sitecore.Data.Items.MediaItem image = new Sitecore.Data.Items.MediaItem(imageField.MediaItem);
string src = Sitecore.StringUtil.EnsurePrefix('/',
Sitecore.Resources.Media.MediaManager.GetMediaUrl(image));
string imgTag = String.Format(@"<img src=""{0}"" alt=""{1}"" />", src, image.Alt);
}
Use the Sitecore media library for images and other media contributed by business users. Use the file system and a source code management system for images managed by developers.
You can use the Sitecore.Data.Fields.ImageField.Clear
method to clear the content of an Image field. For example, to clear the Image field named ImageField
field in the /Sitecore/Content/Home item in the Master database:
Sitecore.Data.Database master = Sitecore.Configuration.Factory.GetDatabase("master");
Sitecore.Data.Items.Item home = master.GetItem("/sitecore/content/home");
Sitecore.Data.Fields.ImageField imageField = home.Fields["imagefield"];
home.Editing.BeginEdit();
imageField.Clear();
home.Editing.EndEdit();
You can use the Sitecore.Data.Fields.ImageField
class to update an Image field. For example, to update the Image field named ImageField
in the /Sitecore/Content/Home item in the Master database to the /Sitecore/Media Library/Images/Sample image:
Sitecore.Data.Database master = Sitecore.Configuration.Factory.GetDatabase("master");
Sitecore.Data.Items.Item home = master.GetItem("/sitecore/content/home");
Sitecore.Data.Items.Item sampleItem =
master.GetItem("/sitecore/media library/images/sample");
Sitecore.Data.Items.MediaItem sampleMedia =
new Sitecore.Data.Items.MediaItem(sampleItem);
Sitecore.Data.Fields.ImageField imageField = home.Fields["imagefield"];
if (imageField.MediaID != sampleMedia.ID) {
home.Editing.BeginEdit();
imageField.Clear();
imageField.MediaID = sampleMedia.ID;
if (!String.IsNullOrEmpty(sampleMedia.Alt))
{
imageField.Alt = sampleMedia.Alt;
}
else
{
imageField.Alt = sampleMedia.DisplayName;
}
home.Editing.EndEdit();
}