Last updated: Apr 10, 2024
Reading time·3 min
The Pillow "OSError: cannot write mode RGBA as JPEG" occurs when you try to
save an image with transparency as jpg
.
JPG images don't support transparency, so use the Image.convert()
method to
convert the image to RGB
.
Here is an example of how the error occurs.
from PIL import Image with Image.open("house.png") as im: rgb_im = im.convert('RGBA') # ⛔️ OSError: cannot write mode RGBA as JPEG rgb_im.save('house.jpg')
We called the Image.convert()
method with a mode of RGBA
.
RGBA stands for red green blue alpha.
The JPG format does not support transparency which causes the error.
One way to solve the error is to call the Image.convert()
method with a mode
of RGB
.
from PIL import Image with Image.open("house.png") as im: # ✅ Set the mode to RGB rgb_im = im.convert('RGB') rgb_im.save('house.jpg')
If you get the error "OSError: cannot write mode P as JPEG", the solution is the same.
The P
mode also has alpha (transparency) and cannot be saved as JPG.
You can use the mode
attribute to check the mode of an image.
from PIL import Image with Image.open("house.png") as im: print(im.mode) # 👉️ P rgb_im = im.convert('RGB') print(rgb_im.mode) # 👉️ RGB rgb_im.save('house.jpg')
The mode of the .png
image is initially P
. However, after calling
Image.convert()
with RGB
as an argument, the mode of the stored in the
rgb_im
variable image is RGB
.
You can also use an if
statement to check if the mode of the image is RGBA
before calling the Image.convert()
method.
from PIL import Image with Image.open("house.png") as im: if im.mode in ('RGBA', 'P'): rgb_im = im.convert('RGB') rgb_im.save('house.jpg') elif im.mode in ('RGB', 'JPEG'): im.save('house123.jpg')
The RGBA and P modes have alpha (transparency) and as previously stated, JPG images don't support alpha (transparency).
The RGB mode does not have alpha and can be saved as JPG.
The example uses the with open() syntax, however, you could also open the image directly.
from PIL import Image im = Image.open('house.png') rgb_im = im.convert('RGB') rgb_im.save('house.jpg')
This can also be shortened to a single line.
from PIL import Image Image.open('house.png').convert('RGB').save('house.jpg')
The Image.convert()
method returns a converted copy of the given image.
The JPG format is not capable of saving any transparencies.
If you need to set transparencies, you have to pick a different format.
The GIF and PNG image formats support transparency.
If you don't necessarily have to store the image as JPG, you could save it as PNG.
from PIL import Image with Image.open("house.png") as im: im.save('house-new.png')
PNG images (and GIFs) support transparency, so you won't run into any issues
when storing RGBA images as .png
.
You can learn more about the related topics by checking out the following tutorials: