使用ModelForm在Pillow上载时调整图像大小

时间:2018-09-05 09:25:51

标签: django django-forms django-rest-framework

嘿,我有以下代码,但是它没有返回错误,但是图像没有被调整大小,开始时是6.2 MB,运行代码后是相同的:

我的模特:

class Photo(models.Model):
    user_name= models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True)
    photo= models.ImageField()
    photo_name= models.TextField(max_length=300)

    def __str__(self):
        return self.photo_name

    def get_absolute_url(self):
        return reverse('photo:add_photo',{'pk':self.pk}) 

我的Model.Form

class PhotoForm(ModelForm):

    def clean_image(self):
        img = self.cleaned_data.get('photo')
        if not img:
            return img
        maxdim = 1024
        if any(dim > maxdim for dim in img.image.size):
            # Resize too large image up to the max_size
            i = Image.open(img.file)
            fmt = i.format.lower()
            i.thumbnail((maxdim, maxdim))
            # We must reset io.BytesIO object, otherwise resized image bytes
            # will get appended to the original image
            img.file = type(img.file)()
            i.save(img.file, fmt)
        return img

    class Meta:
        model = Photo
        exclude= ('user_name',)

我的views.py

class PhotoCreateView(View):
    form_class =  PhotoForm
    template_name = 'photo/photo_form.html'

    def get(self,request):
        form = self.form_class(None)
        return render(request,self.template_name,{'form': form})
    def post(self,request):
        form = self.form_class(request.POST, request.FILES)


        if form.is_valid():

            return redirect('travel:main')

        return render(request, self.template_name,{})

任何人都知道为什么它不返回错误,但是图像仍然具有相同的大小。我想将图像上传到我在pythonanywhere.com上托管的应用程序中,并且图像存储空间限制为512 MB,这不是很多。

2 个答案:

答案 0 :(得分:0)

您可以使用调整大小方法来代替缩略图,如下所示:

def clean_image(self):
        img = self.cleaned_data.get('photo')
        if not img:
            return img
        maxdim = 1024
        if any(dim > maxdim for dim in img.image.size):
            # Resize too large image up to the max_size
            i = Image.open(img.file)
            img = i.resize((maxdim, maxdim), Image.ANTIALIAS)

            img.save(image/file/path)
        return img

答案 1 :(得分:0)

如果您想要一个程序包来保存您确定的不同大小和标签的图像,则可以使用N程序包并像这样使用它们:

models.py:

django-stdimage

some.html:

image = StdImageField(upload_to=upload_to, blank=True, variations={
        'large': (600, 400),
        'thumbnail': (100, 100, True),
        'medium': (300, 200),
    })