Question

I can't work out if it's possible to create the following thumbnail using sorl-thumbnail in a django template:

  • Fixed width, upscaled if necessary.
  • Maximum height. If the resized image is shorter than the max height than I don't mind.
  • I don't want to crop the image width-wise but I don't mind cropping it height-wise.

If I were able to do this in two steps, I would:

  • Resize the image to x width, allowing upscaling.
  • Crop the image to fit within a rectangle x by y.

The best I can do is this, which gets the width looking good but doesn't crop the height.

{% thumbnail banner "1010" crop="center" as im %}<img id='banner' src='{{ im.url }}'/>{% endthumbnail %}

Any ideas?

Was it helpful?

Solution

As far as I know, sorl-thumbnail does not allow you to do that in one step. If you wanted max-height only, you could use the "x100" geometry syntax, but it doesn't ensure fixed width.

I can see three alternatives:

Use the is_portrait filter to find out if you will need cropping or not:

{% if my_img|is_portrait %}
{% thumbnail my_img.filename "100x100" crop="top" as thumb %}
<img src="{{thumb}}" height="{{thumb.height}}" width="{{thumb.width}}"/>
{% endthumbnail %}
{% else %}
{% thumbnail my_img.filename "100" as thumb %}
<img src="{{thumb}}" height="{{thumb.height}}" width="{{thumb.width}}"/>
{% endthumbnail %}
{% endif %}

Make a custom sorl engine to crop at max_height:

from sorl.thumbnail.engines.pil_engine import Engine
class MyCustomEngine(Engine):
    def create(self, image, geometry, options):
      image = super(MyCustomEngine, self).create(image, grometry, options)
      if 'max_height' in options:
          max_height = options['max_height']
          # Do your thing here, crop, measure, etc
      return image

{% thumbnail my_image.filename "100" max_height=100 as thumb %}

Simulate cropping your images via HTML

{% thumbnail my_img.filename "100" crop="top" as thumb %}
<figure><img src="{{thumb}}" height="{{thumb.height}}" width="{{thumb.width}}"/></figure>
{% endthumbnail %}

# Your CSS file
figure {
max-height: 100px;
overflow: hidden;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top