Convert PNG images from folder to JPG - Python

Viewed 2296

Can anyone show me how i can convert all png images in my local folder to jpg images? I've tried using the following code

path1 = r'C:\Users\david.han\Desktop\COPY_images_files' 

path2 = r'C:\Users\david.han\Desktop\JPG converter'

files_to_convert = (f for f in os.listdir(path1) if f.endswith(".png"))
for filename in files_to_convert:
    im = Image.open(os.path.join(path1, filename))
    root, _ = os.path.splitext(filename)
    jpg_file = os.path.join(path2, f'{root}.jpg')
    im.save(jpg_file)

I keep getting this error "OSError: cannot write mode P as JPEG"

2 Answers

I've decided to keep JPG but in case anyone wants to know how to change png to jpg

enter code here

from PIL import Image 
import os 

path = r'C:\Users\david.han\Desktop\COPY_images_files'

for file in os.listdir(path): 
    if file.endswith(".jpg"): 
        img = Image.open(file)
        file_name, file_ext = os.path.splitext(file)
        img.save('/png/{}.png'.format(file_name))

Correction to David's code:

from PIL import Image 
import os 

path = r'enter_path_to_images'

for file in os.listdir(path): 
    if not file.endswith(".jpg"): 
        img = Image.open("{path}/{file}")
        file_name, file_ext = os.path.splitext(file)
        img.save('/png/{}.png'.format(file_name))

In this case, we also need to add the correct path not to get any errors.

Related