Search code examples
shopwareshopware6

Shopware6: Get width and height of thumbnail - from the generated file


I want to add width and height attributes to our image tags in our templates. Unfortunately, when using media.width and media.height, I get the width and height that is entered as the thumbnail size. And not the actual size of the image being used.

Example: We generate a thumbnail with the size 1200 x 1200. But it's a horizontal image, so the size is actual 1200 x 700 px. Now I would like to add width="1200" height="700" to our image tag, but I get 1200 x 1200.

Is there any way to get the actual size in the templates?


Solution

  • The original resolution of an image is stored in the metaData property of the media entity. You'll have to calculate the thumbnail size aspect ratio from the resolution of the original image.

    {% set thumbnail = media.thumbnails.first %}
    {% set oHeight = media.metaData.height %}
    {% set oWidth = media.metaData.width %}
    {% if oHeight > oWidth %}
        {% set ratio = thumbnail.height / oHeight %}
    {% else %}
        {% set ratio = thumbnail.width / oWidth %}
    {% endif %}
    {% set height = oHeight * ratio %}
    {% set width = oWidth * ratio %}
    <img src="{{ thumbnail.url }}"
         height="{{ height|round }}"
         width="{{ width|round }}"/>