Python枕头-裁剪问题()

时间:2020-10-10 17:25:36

标签: python-3.x django python-imaging-library

我正在使用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

当前的问题是图像在前端但在后端没有很好地裁剪。在裁剪的照片中出现黑色区域​​。我想要在前端看到的准确图像。前端和后端的坐标相同。

裁剪后的图像就像this

1 个答案:

答案 0 :(得分:0)

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

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

如果有人有更好的主意,请发表评论。

干杯。