I'm using a transformed image in a context where there's a maximum file size. Is there a way to determine the transformed image's file size in the templates? .size
can't run on the url string
2 Answers
I don't think it's possible to get the file size of an image after it's been transformed with Craft's out-of-the-box image transforms.
It looks like the .size
property only works on the original asset file.
Even if you did something like this...
{% set image = entry.myAssetField.one() %}
{% set thumb = {
mode: 'crop',
width: 100,
height: 100,
quality: 75,
position: 'top-center'
} %}
{% if image %}
{% do image.setTransform(thumb) %}
{{ image.width }} x {{ image.height }} = {{ image.size }} bytes
{% endif %}
.height
and .width
properties will show the transformed dimensions (100 x 100), but .size
outputs the original file size, not the transformed size.
I'm guessing this might be a problem for Craft because the transformed image may not have been generated before the template is rendered.
Update
The Imager plugin has a getSize
method that should work. Imager transforms are created before the template is rendered.
getSize($unit='b', $precision='2') [float]
{{ image.getSize() }} B
{{ image.getSize('k') }} KB
{{ image.getSize('m', 10) }} MB
{{ image.getSize('g', 10) }} GB
-
"the transformed image may not have been generated before the template is rendered" good point. Makes me think that on Craft 3 you might be able to use ImageOptimize to define the transform, since those images are generated in advance… but this site is Craft 2. Thoughts @andrew.welch?– henrySep 12, 2018 at 19:54
-
-
2Small correction, Imager creates the transforms at template render time. So the size will be available, but the template rendering will also block the first time image transforms are made. Ways around this are to use the Preparse field on the backend, or use a service like Imgix. Sep 13, 2018 at 1:29
You can do this via:
Named transforms:
{% someAsset = entry.someAssetField.one() %}
{% if someAsset | length %}
{{ someAsset.getHeight('transformName') }}
{{ someAsset.getWidth('transformName') }}
{% endif %}
Template transforms:
{% someAsset = entry.someAssetField.one() %}
{% if someAsset | length %}
{{ someAsset.getHeight(transformConfig) }}
{{ someAsset.getWidth(transformConfig) }}
{% endif %}
-
This answer seems to be related to image dimensions, not the image's file size (bytes) as the question's title implies. Sep 12, 2018 at 17:51
-
-