如何在Django的FileField中查找图像的高度和宽度

7

如果我们的模型定义如下,如何找到图像的高度和宽度

class MModel:
 document = FileField()
 format_type = CharField()

如果图像被保存在文档中,那么如何找到文档的高度和宽度,如果它是图像?

1
你可以将其更改为 ImageField 并使用 width_fieldheight_field 参数。 - Selcuk
你是不是想要使用 ImageField(MModel.objects.all()[0]).height? - Paras Meena
1个回答

23
如果文件始终为图像,则将FileField更改为ImageField,就像这样:
def MyModel(models.Model):
  height = models.IntegerField()
  width = models.IntegerField()
  document = models.ImageField(height_field='height', width_field='width')
否则,你将不得不手动计算图像的宽度和高度:
from django.core.files.images import get_image_dimensions

obj = MModel.objects.get(pk=1)
width, height = get_image_dimensions(obj.document.file)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接