Reputation: 59
I'm trying to convert all image files within a folder to jpg using Pillow.
I'm new to pillow so I'm not 100% on my grasp of the concepts.
Here are the functions I'm using:
def convert_jpg(file, folder = 'flag_images/', delete = False):
filepath = folder + file
print(file)
img = Image.open(filepath, mode = 'r')
if delete:
img.save(folder + 'backup/' + file)
os.remove(filepath)
if img.mode != 'RGB':
img.convert('RBG')
filepath = filepath[0:-3] + 'jpg'
img.save(filepath)
def convert_all(folder = 'flag_images/'):
for filename in os.listdir(os.path.abspath(os.getcwd()) + '/flag_images'):
if filename[-3:] != 'jpg':
convert_jpg(file = filename, folder = folder, delete = True)
When running convert_all, I get the following error when I get to a file with mode 'P':
ValueError Traceback (most recent call last)
~/anaconda3/lib/python3.8/site-packages/PIL/Image.py in convert(self, mode, matrix, dither, palette, colors)
1025 try:
-> 1026 im = self.im.convert(mode, dither)
1027 except ValueError:
ValueError: conversion not supported
How can I successfully convert the mode to RGB, so that I can save as a jpg?
Upvotes: 0
Views: 4033
Reputation: 207465
You have a typo and a usage error. You'd need to change this:
img.convert('RBG')
to this:
img = img.convert('RGB')
That said, it shouldn't be necessary at all, since JPEG is necessarily not P
mode.
Upvotes: 1