TransWikia.com

Can you prevent upscaling when using Craft's image transforms?

Craft CMS Asked by Simon East on January 5, 2021

With Craft’s image transforms used to resize images or generate thumbnails, can you prevent images from being upscaled? There’s often cases where it makes no sense to increase the dimensions of an image.

It would be great if there was a setting for this, but I can’t find one documented.

Otherwise, is the solution to fetch the image size in Twig and then conditionally apply the image transform?

3 Answers

As found here, this actually seems to be a requested feature that is not yet implemented. However, in the link given, Brandon also supplied a workaround for the time being:

{% set transform = {
width: min(150, image.width),
height: min(100, image.height)
} %}

<img src="{{ image.getUrl(transform) }}">

Correct answer by justussimon91 on January 5, 2021

As of Craft 3.4 you can set upscaleImages to false in general config: https://craftcms.com/docs/3.x/config/config-settings.html#upscaleimages

Answered by James Smith on January 5, 2021

If you want to work with transforms you've created in the backend you can use this:

{% set transformDimensions = craft.app.assetTransforms.getTransformByHandle('contentWidth') %}
{% set transform = {
    width: min(transformDimensions.width, image.width),
    mode: 'fit'
} %}

<img src="{{ image.url(transform) }}" alt="" />

Answered by outline4 on January 5, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP