【问题标题】:How to set a fixed width, maximum height using sorl-thumbnail (in Django)如何使用 sorl-thumbnail(在 Django 中)设置固定宽度、最大高度
【发布时间】:2011-12-18 22:18:19
【问题描述】:

我不知道是否可以在 django 模板中使用 sorl-thumbnail 创建以下缩略图:

  • 固定宽度,必要时放大。
  • 最大高度。如果调整后的图像比最大高度短我不介意。
  • 我不想按宽度裁剪图像,但不介意按高度裁剪。

如果我能够分两步做到这一点,我会:

  • 将图像大小调整为 x 宽度,允许放大。
  • 裁剪图像以适应 x x y 的矩形。

我能做的最好的就是这样,它使宽度看起来不错,但不会裁剪高度。

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

有什么想法吗?

【问题讨论】:

    标签: django-templates sorl-thumbnail


    【解决方案1】:

    据我所知,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;
    }
    

    【讨论】:

    • 哇,不是一个答案,而是三个!谢谢,真的很有帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-21
    • 2013-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-15
    相关资源
    最近更新 更多