【问题标题】:Accessing image dimensions on an ImageField in a Django template?在 Django 模板中访问 ImageField 上的图像尺寸?
【发布时间】:2011-07-28 05:08:44
【问题描述】:

我的模型中有ImageField,我可以在模板中显示图像。但是,如何检索图像的高度和宽度?

【问题讨论】:

标签: django image dimensions


【解决方案1】:

请参阅ImageField 的文档。

除了特殊属性 可用于 FileField,一个 ImageField 也有高度和宽度 属性。

所以只需执行以下操作:

<img src="{{ image.url }}" width="{{ image.width }}" height="{{ image.height }}"/>

【讨论】:

  • hmmm .. 它对我不起作用。 {% with post.postimage_set.all as image %}&lt;a href="{{ image.get_image_url }}"&gt;&lt;img src="{{ image.get_image_url }}" title="{{ image.title }}" alt="{{ alt }}" width="{{ image.width }}" height="{{ image.height }}" /&gt;&lt;/a&gt;{% endwith %}
【解决方案2】:

在我的例子中,为了使 width 和 height 字段起作用,我需要设置 ImageField 的 width_field 和 height_field

例如

class Product(models.Model):
    image = models.ImageField(width_field='image_width', height_field='image_height')
    image_width = models.IntegerField()
    image_height = models.IntegerField()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-25
    • 2015-09-19
    • 2020-03-03
    • 2014-08-31
    相关资源
    最近更新 更多