Get Image dimensions in template

I want to use photoswipe on a site and need the image dimensions (width, height). I have found no information on how to access those informations except for a five year old question which was answered with an imageWidth attribute which does not exist (anymore).

Can anybody help?

Hi @Aram

The |imageWidth filters were too bad for performance, and we don’t recommend using the server to determine the width of an image. We plan on reintroducing this functionality when the media manager is updated, we will capture the information early instead of compiling it at runtime.

It might be possible to bring it back using a plugin. Can you share the ideal Twig that you would need?

In my case I want to build a Photoswipe Gallery which needs some data-attributes containing the width and height of the target image.

What I find a bit strange is the fact that If I loop over my images (which were added using tailor and a mediafinder input) is that it seems to return only a string containing the filename. Is that true or only the case when using tailor?

I would somehow expect it to return an image model of some sorts which would then be able to get the image dimensions if needed.

But thinking about it, it would ideally be some sort of filter; because I can also imagine wanting to know the exact width or height after resizing.
For Example:

image|media|resize(256,256)|width or image|width

This is true for mediafinder’s output, it will store the media paths as a simple PHP array. The fileupload will return a complete File model object.

Ideally, the Photoswipe gallery can determine the width and height using JavaScript after loading the image. The demo theme uses the Photoswipe control fine without it. Can you point us to the relevant documentation for needing the attributes up front?

I’m adding my 2 cent as I saw that post finding a way to get image dimensions of fileupload model object.

I think calculating size using javascript is not a good solution as today, most images are lazyloaded and javascript will not know the image dimensions without loading it, so it does not prevent content jumping.

The best solution would be to calculate the image width and height when after uploading the image in backend, and add a width and height attribute to the file model object.

Then, in frontend, that dimensions would be accessible like any other attributes

2 Likes

@Zmove

This is a great idea, thanks for sharing.