Craft CMS Stack Exchange is a question and answer site for administrators, end users, developers and designers for Craft CMS. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

There is almost never a reason why I would want an image to be scaled past 100% by a transform. This usually results in an image being looking worse than it would if scaled by the browser. Is there a way to tell Craft not to scale an image past 100% of its original size, even if the transform width is larger?

share|improve this question
    
Please vote for this feature request to prevent transforms from scaling up! feedback.craftcms.com/forums/285221-feature-requests/… – Lindsey D 2 days ago
up vote 8 down vote accepted

Yes.

getWidth will give you an image's width: {% set originalWidth = image.getWidth(false) %}. You want to apply the transform if desiredWidth is less than originalWidth. I would write a twig macro:

{% macro transform(image, desiredWidth) %}
  {% set originalWidth = image.getWidth(false) %}
  {% if desiredWidth < originalWidth %}
    {{ image.getUrl({mode: 'fit', width: desiredWidth}) }}
  {% else %}
    {{ image.getUrl() }}
  {% endif %}
{% endmacro %}

You could also do the same test, and then conditionally setTransform on the image.

If you define your transforms in the CP the macro would be like this:

{% macro transform(image, transformHandle) %}
  {% set originalWidth = image.getWidth(false) %}
  {% set transformedWidth = image.getWidth(transformHandle) %}
  {% if transformedWidth < originalWidth %}
    {{ image.getUrl(transformHandle) }}
  {% else %}
    {{ image.getUrl() }}
  {% endif %}
{% endmacro %}
share|improve this answer
2  
Good answer. Would be nice, though, if this was a setting built into Transforms. – cmal Jul 27 '14 at 19:26
1  
@cmal it looks like a setting to prevent upscaling is already on "The List". – carlcs Jul 27 '14 at 21:43
    
Thanks @ChristianSeelbach that's great news. – cmal Jul 27 '14 at 23:08

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.