【问题标题】:How can I get the uploaded image's width and height in django?如何在 django 中获取上传图像的宽度和高度?
【发布时间】:2013-07-22 02:18:42
【问题描述】:

如何在django中获取上传图片的宽高?

不要使用 PIL。

【问题讨论】:

  • 为什么不允许使用 PIL?这正是它的用途。
  • 然后使用Pillow
  • 我的意思是不要使用其他包,只使用 django。 django 中是否有方法或属性可以像 request.FILES['filename'].name 一样简单地获取上传图像的宽度和高度

标签: django image-upload


【解决方案1】:

ImageField 会自动处理图片的宽高。你不需要做任何事情。

  1. 更改项目设置

将这些代码添加到项目目录中setting.py的末尾

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

然后改项目目录下的urls.py

urlpatterns = [
    path('admin/', admin.site.urls),
    path(...),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
  1. 提供两个整数字段来存储图像的宽度和高度

models.py

class Picture(models.Model):
    image = models.ImageField(upload_to='images/', width_field = 'image_width', height_field='image_height')
    image_width = models.IntegerField(default=0)
    image_height = models.IntegerField(default=0)
  1. 创建一个表单,不要包含“image_width”和“image_height”,它们应该是隐藏和自动填充的。

forms.py

class PictureForm(forms.Form)
    image = forms.ImageField()
  1. 在视图中验证和处理表单并将数据保存到数据库中

views.py

def createPicture(request):
    form = PictureForm(request.POST, request.FILES)
    if form.is_valid():
        picture = Picture()
        picture.image = form.cleaned_data['image']
        picture.save()
        return HttpResponseRedirect(reverse('picture-list'))
    else:
        form = PictureForm()
    return render(request, 'template_file', {'form' : form})

【讨论】:

    【解决方案2】:

    委托给专门用于处理图像的包。比如PIL。

    【讨论】:

      【解决方案3】:

      Django 有ImageField 会自动执行此计算,但您需要安装 PIL。

      设置完成后,您将自动获得图像的heightwidth 属性,因此您可以这样做:

      class SomeModel(models.Model):
         img = models.ImageField(upload_to='images/')
      
      foo = SomeModel.objects.get(pk=1)
      print('The height is {0.height} and the width is {0.width}'.format(foo.img))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-11-07
        • 2016-05-08
        • 1970-01-01
        • 2011-05-31
        • 1970-01-01
        • 2010-11-18
        • 1970-01-01
        相关资源
        最近更新 更多