Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting all files (.jpg to .png) from a directory in Python

I'm trying to convert all files from a directory from .jpg to .png. The name should remain the same, just the format would change.

I've been doing some researches and came to this:

from PIL import Image
import os

directory = r'D:\PATH'

for filename in os.listdir(directory):
    if filename.endswith(".jpg"):
        im = Image.open(filename)
        im.save('img11.png')
        print(os.path.join(directory, filename))
        continue
    else:
        continue

I was expecting the loop to go through all my .jpg files and convert them to .png files. So far I was doing only with 1 name: 'img11.png', I haven't succed to build something able to write the adequate names.

The print(os.path.join(directory, filename)) works, it prints all my files but concerning the converting part, it only works for 1 file.

Do you guys have any idea for helping me going through the process?

like image 443
Grégoire de Kermel Avatar asked Jul 26 '19 10:07

Grégoire de Kermel


2 Answers

You can convert the opened image as RGB and then you can save it in any format. You can try the following code :

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
like image 92
Aditya Singh Avatar answered Oct 04 '22 10:10

Aditya Singh


You're explicitly saving every file as img11.png. You should get the name of your jpg file and then use that to name and save the png file.

name = filename[:-4]
im.save(name + '.png')
like image 44
Arienrhod Avatar answered Oct 04 '22 10:10

Arienrhod