python-3.x - 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
目前的问题是图像在前端被裁剪得很好,但在后端却没有。我在裁剪的图片中得到黑色区域。我想要我在前端看到的精确图像。前端和后端的坐标相同。
解决方案
最后在花了几个小时试图解决这个问题后,我找到了原因。
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
如果有人有更好的想法,请发表评论。
干杯。
推荐阅读
- perl - 无法对 D:\ImageMark\opt\siips\classa\patches\alter_db.pl 第 421 行的未定义值调用方法“执行”
- java-8 - 使用 VariablePrepare 规范化 docx4j
- javascript - 在 JQuery 中分别处理每个第 n 个元素
- regex - 门牌号的正则表达式
- spring - 找不到合适的 NamedParameterJdbcTemplate bean
- perl - Perl 的 XML::Compile::WSDL11 -> importDefinitions() 不保存命名空间
- java - 实践中的并发 > 清单 4.13
- raspberry-pi - BCM2835 数据表寻址系统
- rename - 按顺序重命名 tif 文件
- ios - Websockets:连接被拒绝,但客户端和服务器都与其他客户端和服务器一起工作