convert png to jpg folder python code example

Example 1: python convert png to jpg

from PIL import Image

img = Image.open('image.png')
rgb_img = img.convert('RGB')
rgb_img.save('image.jpg')

Example 2: convert files from jpg to png and save in a new directory python

from PIL import Image
import os

directory = r'D:\PATH'
c=1
for filename in os.listdir(directory):
    if filename.endswith(".jpg"):
        im = Image.open(filename)
        name='img'+str(c)+'.png'
        rgb_im = im.convert('RGB')
        rgb_im.save(name)
        c+=1
        print(os.path.join(directory, filename))
        continue
    else:
        continue