Aspect_ratio for images that aren't objects

Is there any way to access the dimensions or aspect ratio of an image that’s “just” stored in the files?

I’m trying to add the height and width to images, and doing so manually would be time consuming and hard to maintain. It’s simple to do when the image is part of an object:

...
width="973"
height="{{ 973 | divided_by: media.aspect_ratio | ceil }}"
...

But accessing it via file_img_url doesn’t seem to hold any useful information.

Is there any way to do this?

Many thanks!

Hi @materangai7 ,

Can you explain more about it? Are you trying to add width and height like the code you send for images uploaded in Customize? Or for product images.

And please send your site and if your site is password protected, please send me the password. I will check it.

It’s for images that have been uploaded directly to the files section, so all that’s known is the name and url.

You can retrieve the image file aspect_ratio by using images[‘filename’]

It should look something like this

{{ images['myfile.png'].aspect_ratio }}

Reference: https://shopify.dev/api/liquid/objects/images

2 Likes

Thank you :slightly_smiling_face:

@JSLee

That is very helpful, thank you. I have developed a solution for this as well, in case anyone needs help.

It extracts the image’s file name from the metafield value and transforms it into an image object:

{% assign __name = collection.metafields.custom.banner_image | file_url | split: 'files/' %}
{% assign _name = __name[2] | split: '?' %}
{% assign metafield_filename = _name[0] | strip %}
{% assign metafield_filename_length = metafield_filename | size %}

{% if metafield_filename_length >= 1 %}
  {{ images[metafield_filename].aspect_ratio }}
{% endif %}
1 Like