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

how to find height and width of image for FileField Django

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

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

并且图像保存在文档中,那么如果是图像,我们如何找到文档的高度和宽度?

如果文件始终是图像,请将 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)