django-avatar icon indicating copy to clipboard operation
django-avatar copied to clipboard

OSError: cannot write mode RGBA as JPEG

Open vonmaster opened this issue 4 years ago • 1 comments

Hi,

This pull request #75 is causing an issue OSError: cannot write mode RGBA as JPEG, when uploading a PNG with a RGBA mode. The issue is uncaught/silenced due to the try except block and it prevents avatars from being resized (displaying broken images).

I suggest to revert to the previous state, please do so:

if image.mode != "RGB":
    image = image.convert("RGB")

Detail Error Log:

>>> from django.utils import six
>>> thumb = six.BytesIO()
>>> image.save(thumb, settings.AVATAR_THUMB_FORMAT, quality=quality)
Traceback (most recent call last):
  File "/opt/python/run/venv/local/lib64/python3.6/site-packages/PIL/JpegImagePlugin.py", line 611, in _save
    rawmode = RAWMODE[im.mode]
KeyError: 'RGBA'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/usr/lib64/python3.6/code.py", line 91, in runcode
    exec(code, self.locals)
  File "<console>", line 1, in <module>
  File "/opt/python/run/venv/local/lib64/python3.6/site-packages/PIL/Image.py", line 2151, in save
    save_handler(self, fp, filename)
  File "/opt/python/run/venv/local/lib64/python3.6/site-packages/PIL/JpegImagePlugin.py", line 613, in _save
    raise OSError(f"cannot write mode {im.mode} as JPEG") from e
OSError: cannot write mode RGBA as JPEG
>>> image.mode
'RGBA'
>>> image.mode not in ("RGB", "RGBA")

vonmaster avatar Dec 06 '20 13:12 vonmaster

I used this:

modes = ("RGB",) if settings.AVATAR_THUMB_FORMAT == "JPEG" else ("RGB","RGBA")

if image.mode not in modes:
    image = image.convert("RGB")

That retains the functionality from PR #75 by preserving RGBA if AVATAR_THUMB_FORMAT isn't JPEG, but forces RGB if it is JPEG (the default).

elementgreen avatar Dec 13 '20 19:12 elementgreen

Fixed in version 6.0.0.

johanneswilm avatar Aug 12 '22 05:08 johanneswilm