Fixing OSError: cannot write mode RGBA as JPEG in Python

I have an application that was originally written in Python 2.7 and used the Python Image Libary (PIL). Now it uses Python 3.x and Pillow (the PIL replacement). One of the things it does is automatically generate .jpg file thumbnails of uploaded files.

It does this by resizing the uploaded image, and then saving it with the filename extension changed.

I started getting an error when uploading a .png file:

OSError: cannot write mode RGBA as JPEG

A bit of research told me that the behavior has changed. Now you need to discard the alpha (transparency) channel of an image before you’re allowed to save it as an image type that doesn’t have an alpha channel. Since PNG files normally have a transparency layer, it makes sense why I would hit that error. It’s trying to protect me from losing data I might potentially want to keep. However, I don’t want or need alpha channel data for my thumbnails.

The solution is just to convert the image before saving.

thumbnail = im.convert('RGB')
thumbnail.save("my_image_filename.jpg", 'JPEG', quality=92)

It’s a simple fix, but slightly annoying that the behavior has changed over the years.