Search code examples
sitecoresitecore8sitecore-mvcimagefield

How to get the size of the image field in sitecore 8?


I tried to get the size of my image field in sitecore, but am not able to achieve.

I can take the height and width of the image by using below code.

@{
   Sitecore.Data.Items.Item curItem = Sitecore.Context.Item;
   Sitecore.Data.Fields.ImageField field = curItem.Fields["Image"];
}
<p>Height: @field.Height</p>
<p>Width: @field.Width</p>

But how to get the size..?


Solution

  • You cannot get image size from the field directly, but you can get it from the linked media item:

    @{
        long size = -1;
        Sitecore.Data.Items.Item curItem = Sitecore.Context.Item;
        Sitecore.Data.Fields.ImageField field = curItem.Fields["Image"];
        MediaItem mediaItem = field.MediaItem;
        if (mediaItem != null)
        {
            size = mediaItem.Size;
        }
    }
    
    <p>Height: @field.Height</p>
    <p>Width: @field.Width</p>
    <p>Size: @size</p>