【问题标题】:Python Pillow - Facing issue with crop()Python Pillow - 面临crop() 的问题
【发布时间】:2020-10-11 14:23:53
【问题描述】:

我正在使用 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.x django python-imaging-library


    【解决方案1】:

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

    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
    

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

    干杯。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-26
      • 2020-07-26
      • 2018-08-22
      • 2016-05-11
      • 2020-07-09
      • 1970-01-01
      相关资源
      最近更新 更多