2

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..?

Marek Musielak
  • 26,832
  • 8
  • 72
  • 80
Ramesh
  • 1,073
  • 6
  • 24
  • 53

1 Answers1

5

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>
Marek Musielak
  • 26,832
  • 8
  • 72
  • 80
  • Is there a way to do this using the MediaItem? I'm pulling images directly from the Media Library using a controller and need to display the dimensions in the view but I dont see a way of getting it from the MediaItem or the MediaManager. – Necromancer Dec 19 '18 at 19:32
  • That only gives me the file size of the media item, I need Width and Height. – Necromancer Dec 19 '18 at 20:00
  • 1
    MediaItem is generic. It can be image, but it can be a pdf file or even a zip file. That's why it doesn't expose Width and Height. But you can easily get them using `mediaItem.InnerItem["Width"]` and `mediaItem.InnerItem["Height"]` – Marek Musielak Dec 19 '18 at 21:03