Kamran
Kamran

Reputation: 4100

Sitecore fast way to check the mediaItem in the Media Library is an Image or a picture

For the item in Sitecore 'Media Library':

MediaItem mediaItem = Sitecore.Context.Database.GetItem("{E47591D0-48D2-4543-80E4-3836B02AA1A8}");  

The above item is a picture "Tulips.jpg".

How can I check, from code behind, that the above item is actually a Picture/Image?

Upvotes: 2

Views: 2497

Answers (3)

Jonathan Robbins
Jonathan Robbins

Reputation: 2047

An alternative to Dmytro Shevchenko suggestion is to use Sitecore's API to check the Template of the MediaItem containing the image opposed to doing a string comparison.

When an Image is uploaded to the MediaLibrary it is stored an versioned or unversioned template and either Image or jpeg.

So to check if the mediaItem is an image you can do the following;

public ID ImageUnversioned = new ID("{F1828A2C-7E5D-4BBD-98CA-320474871548}");
public ID JpegUnversioned = new ID("{DAF085E8-602E-43A6-8299-038FF171349F}");
public ID ImageVersioned = new ID("{C97BA923-8009-4858-BDD5-D8BE5FCCECF7}");
public ID JpegVersioned = new ID("{EB3FB96C-D56B-4AC9-97F8-F07B24BB9BF7}");

public bool IsImage(Item mediaItem)
{
    return mediaItem.TemplateID.Equals(ImageUnversioned)
           || mediaItem.TemplateID.Equals(JpegUnversioned)
           || mediaItem.TemplateID.Equals(ImageVersioned)
           || mediaItem.TemplateID.Equals(JpegVersioned);
}

Then simply pass in the mediaItem as below;

bool isImageOrPicture = IsImage(mediaItem);

Update

Dmytro Shevchenko made a great point of recursively checking all base templates of the item, as the Jpeg Template descends from the Image template. Implementing as such:

using Sitecore;
using Sitecore.Data.Items;

...

public static bool IsImage(Item item)
{
    if (item.TemplateID == TemplateIDs.VersionedImage 
        || item.TemplateID == TemplateIDs.UnversionedImage)
    {
        return true;
    }

    foreach (TemplateItem baseTemplate in item.Template.BaseTemplates)
    {
        if (IsImage(baseTemplate))
        {
            return true;
        }
    }

    return false;
}

Upvotes: 2

Dmytro Shevchenko
Dmytro Shevchenko

Reputation: 34641

Once you have your MediaItem object, you can do this:

MediaItem mediaItem = ...

bool isPicture = mediaItem.MimeType.StartsWith("image/");

This works because MIME types of images are formed like this: image/.... For example:

  • image/bmp
  • image/gif
  • image/jpeg

Upvotes: 7

Wesley Lomax
Wesley Lomax

Reputation: 2077

Sitecore has a helper on the Sitecore Item class IsMediaItem

Sitecore.Context.Item.Paths.IsMediaItem

This code checks whether the item has a path containing “sitecore/Media library”

You could check the item before converting it to a media item.

Upvotes: 1

Related Questions