首页 > 解决方案 > Python Pillow - 面临crop() 的问题

问题描述

我正在使用 jquery-cropper.js 在前端裁剪图像,然后将值传递给 Django 表单,如下所示。

def save(self):
    photo = super(MyModelForm, self).save()

    x = self.cleaned_data.get('x')
    y = self.cleaned_data.get('y')
    w = self.cleaned_data.get('width')
    h = self.cleaned_data.get('height')


    image = Image.open(photo.profile_pic)

    cropped_image = image.crop((int(x), int(y), int(w+x), int(h+y)))
    cropped_image.save(photo.profile_pic.path)

    #resized_image = cropped_image.resize((min(new_width, new_height), min(new_width, new_height)), Image.LANCZOS)
    #resized_image.save(photo.profile_pic.path)

    return photo

目前的问题是图像在前端被裁剪得很好,但在后端却没有。我在裁剪的图片中得到黑色区域。我想要我在前端看到的精确图像。前端和后端的坐标相同。

裁剪后的图像就像这个

标签: python-3.xdjangopython-imaging-library

解决方案


最后在花了几个小时试图解决这个问题后,我找到了原因。

save()提交表单时,该方法被调用两次。这会导致该crop()方法运行两次并破坏图像。现在我正在使用一个标志来跟踪是否crop()已经调用过一次。

cropFlag = 0

def save(self):
photo = super(MyModelForm, self).save()
if self.cropFlag == 0:
    x = self.cleaned_data.get('x')
    y = self.cleaned_data.get('y')
    w = self.cleaned_data.get('width')
    h = self.cleaned_data.get('height')


   image = Image.open(photo.profile_pic)

   cropped_image = image.crop((int(x), int(y), int(w+x), int(h+y)))
   cropped_image.save(photo.profile_pic.path)

   self.cropFlag = self.cropFlag + 1

return photo

如果有人有更好的想法,请发表评论。

干杯。


推荐阅读