如何在django中获取上传图片的宽度和高度?
不要使用PIL。
答案 0 :(得分:0)
委托专门用于处理图像的包。比如PIL。
答案 1 :(得分:0)
Django有ImageField
会自动执行此计算,但您需要安装PIL。
设置完毕后,系统会自动为您的图片获取height
和width
属性,因此您可以这样做:
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))
答案 2 :(得分:0)
ImageField将自动处理图像的宽度和高度。您不需要做任何事情。
将这些代码附加到项目目录中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)
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)
forms.py
class PictureForm(forms.Form)
image = forms.ImageField()
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})