如何在上传时自动调整图像大小并自动保存django?

时间:2016-10-18 12:40:08

标签: python django

我无法保存要调整大小的图片或直接通过我的admin面板上传的图片。我想通过PLP或任何其他方式调整大小!

def get_product_image_folder(instance, filename):

return "static/images/product/%s/base/%s" %(instance.product_id, filename)
product_image  = StringIO.StringIO(i.read())
imageImage = Image.open(product_image)

thumbImage = imageImage.resize((100,100))

thumbfile = StringIO()
thumbImage.save(thumbfile, "JPEG")

thumbcontent = ContentFile(thumbfile.getvalue())

newphoto.thumb.save(filename, thumbcontent)
new_photo.save()

1 个答案:

答案 0 :(得分:0)

这可以在模型的save方法,admin的save_model方法或表单的save方法中完成。

我推荐最后一个,因为它允许您从模型和管理界面中分离表单/验证逻辑。

这可能如下所示:

class MyForm(forms.ModelForm):
    model = MyModel

    ...
    def save(self, *args, **options):
        if self.cleaned_data.get("image_field"):
            image = self.cleaned_data['image_field']
            image = self.resize_image(image)
            self.cleaned_data['image_field'] = image
        super(MyForm, self).save(*args, **options)

    def resize_image(self, image):
        filepath = image.file.path
        pil_image = PIL.Image.open(filepath)
        resized_image = # **similar steps to what you have in your question
        return resized_image

您可以将此新图像放在cleaning_data字典中以便自行保存,也可以将其保存到模型上具有editable = False的新字段(类似“my_field_thumbnail”)。

有关使用PIL调整图像大小的实际过程的更多信息可以在其他SO问题中找到,例如: How do I resize an image using PIL and maintain its aspect ratio?