我使用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目前的问题是,图像在前端被裁剪得很好,但在后端却不能。我在裁剪过的照片中看到黑色区域。我想要准确的图像,正如我在前端看到的。前端和后端的坐标是相同的。
裁剪后的图像如下所示

发布于 2020-10-11 14:23:53
最后,在花了几个小时试图解决这个问题后,我找到了原因。
当提交表单时,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如果任何人有更好的想法,请评论。
干杯。
https://stackoverflow.com/questions/64296283
复制相似问题