What the slider shows
Left of the handle is what img.convert("RGB") gives: the alpha channel is simply thrown away, and every
transparent pixel shows whatever colour is stored underneath it. Most editors store black there, some store white or leftover
pixels, so the result depends on the file. Right of the handle is the image composited onto your background colour, which is what
the script does: semi-transparent edge pixels are blended correctly instead of turning into a dark fringe.
The browser preview cannot see the colour hidden under fully transparent pixels and shows it as black. Press Run with real Pillow with “Also save the plain convert() result” ticked to see exactly what Pillow produces for your file.
Why Pillow raises "cannot write mode RGBA as JPEG"
JPEG stores three channels and no transparency. Rather than silently guessing a background, Pillow raises
OSError: cannot write mode RGBA as JPEG (and the same for LA, and P images with
transparency). The fix is always the same decision: which colour should the transparent parts become? The
full error page covers the other modes that fail (F,
I;16, CMYK and more), with tested fixes.
What the script handles for you
- Every transparent mode:
RGBA, greyscale with alpha (LA) and palette images with a transparent colour (P, from GIFs and small PNGs) are all composited onto the background. - Phone photos stored sideways are turned upright first with
ImageOps.exif_transpose(). - 16-bit images are scaled to 8 bits; a plain
convert("RGB")would clip them to white. - JPEG input is saved as
name_flat.jpg, so the script never overwrites your original.
If you need to keep the transparency
Do not use JPEG. Save as PNG, WebP or AVIF, which all keep alpha; WebP and AVIF are also much smaller than PNG for photos. The format comparison has measured sizes, and converting formats shows the settings.
Converting a whole folder
Wrap the script's flattening lines in a function and loop over files, as in processing all images in a folder, which also shows how to skip broken files and keep EXIF orientation.