Akut Luna
Akut Luna

Reputation: 359

Why do I get "cannot save mode RGBA" error when using PIL?

I am tring to convert images in to a PDF. I have this code:

def convertToPDF(folder, PDFname, deleteLast=False):
    '''
    converts all images in a folder to a PDF. 
    '''
    imageList = []
    for filename in glob.glob(folder + f'/*'):
        image=Image.open(filename)
        image.convert('RGB') # convert to RGB
        imageList.append(image)

    imageList[0].save(f'./' + PDFname + '.pdf',save_all=True, append_images=imageList[1:]) # take the first image and add everything else

and I get this error sometimes:

 File "c:\Users\felix\OneDrive\Desktop\Programmieren\TelegrammBotProjekt\manganeloAPI.py", line 195, in convertToPDF
   imageList[0].save(f'./' + PDFname + '.pdf',save_all=True, append_images=imageList[1:]) # take the first image and add everything else
 File "C:\Users\felix\Anaconda3\lib\site-packages\PIL\Image.py", line 2151, in save
   save_handler(self, fp, filename)
 File "C:\Users\felix\Anaconda3\lib\site-packages\PIL\PdfImagePlugin.py", line 41, in _save_all
   _save(im, fp, filename, save_all=True)
 File "C:\Users\felix\Anaconda3\lib\site-packages\PIL\PdfImagePlugin.py", line 156, in _save
   raise ValueError(f"cannot save mode {im.mode}")
ValueError: cannot save mode RGBA

Has someone an idea what the problem is and how to fix it? I thought I'm already converting each image to 'RGB'. So, why do I get this error?

Upvotes: 9

Views: 8616

Answers (2)

XitXat
XitXat

Reputation: 57

from PIL import Image
import os

def convert_images_to_pdf(images_folder, pdf_file):
    images = []
    for file in os.listdir(images_folder):
        if file.endswith(".jpg") or file.endswith(".png"):
            image = Image.open(os.path.join(images_folder, file))
            if image.mode == 'RGBA':
                image = image.convert('RGB')
            images.append(image)
    images[0].save(pdf_file, save_all=True, append_images=images[1:])

convert_images_to_pdf('images', 'images.pdf')

Upvotes: 2

MatsLindh
MatsLindh

Reputation: 52822

.convert('RGB') does not convert between RGB and RGBA; it's meant to convert between RGB images and images based on a palette (it's main operations is P for palette, L for single channel (grayscale) and RGB for separate channels).

Instead you have to be explicit about making the conversion to drop the alpha channel. From the linked answer:

from PIL import Image

png = Image.open(object.logo.path)
png.load() # required for png.split()

background = Image.new("RGB", png.size, (255, 255, 255))
background.paste(png, mask=png.split()[3]) # 3 is the alpha channel

You can then use background in your image list and save that to the PDF. You've now also explicitly made those images have a white background.

Upvotes: 9

Related Questions