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

Par*_*ena 0 python django image models filefield

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

class MModel:
 document = FileField()
 format_type = CharField()
Run Code Online (Sandbox Code Playgroud)

和图像保存在文档中然后如果它是图像我们如何找到文档的高度和宽度?

Bur*_*lid 9

如果文件始终是图像,请更改FileFieldImageField,如下所示:

def MyModel(models.Model):
  height = models.IntegerField()
  width = models.IntegerField()
  document = models.ImageField(height_field='height', width_field='width')
Run Code Online (Sandbox Code Playgroud)

否则,您必须手动计算图像的宽度和高度:

from django.core.files.images import get_image_dimensions

obj = MModel.objects.get(pk=1)
width, height = get_image_dimensions(obj.document.file)
Run Code Online (Sandbox Code Playgroud)