据我所知,sorl-thumbnail 不允许您一步完成。如果您只想要最大高度,您可以使用“x100”几何语法,但它不能确保固定宽度。
我可以看到三种选择:
使用 is_portrait 过滤器确定是否需要裁剪:
{% 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 %}
制作一个自定义 sorl 引擎以在 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 %}
模拟通过 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;
}