图像转换 - 无法将 RGBA 模式写入 JPEG

6 python django

我正在尝试在项目上传之前调整图像大小并降低图像质量。这是我尝试过的,

def save(self):
    im = Image.open(self.image)
    output = BytesIO()
    im = im.resize(240, 240)
    im.save(output, format='JPEG', quality=95)
    output.seek(0)
    self.image = InMemoryUploadedFile(output, 'ImageField', "%s.jpg" % self.image.name.split('.')[0], 'image/jpeg', sys.getsizeof(output), None)
    super(Model, self).save()
Run Code Online (Sandbox Code Playgroud)

如果我上传jpg图像,它工作正常,但如果我上传png或任何其他图像类型,它就不起作用,它会引发诸如cannot write mode RGBA as JPEG&之类的错误cannot write mode P as JPEG

我们怎样才能解决这个问题?谢谢你!

tim*_*mop 15

If your image.mode is "P" or "RGBA" and you want to convert it to jpeg then you need to first convert the image.mode because the previous modes aren't supported for jpeg

if im.mode in ("RGBA", "P"):
    im = im.convert("RGB")
Run Code Online (Sandbox Code Playgroud)

https://github.com/python-pillow/Pillow/issues/2609