How can I edit all images inside of a directory with python with pillow?

Viewed 158

I have some images with 24 bit depth that I should convert them to 8 bit depth. So I can do it for one image but for multiple images I get this error :

 a=img.convert("P", palette=Image.ADAPTIVE, colors=8)
AttributeError: 'list' object has no attribute 'convert'

image:image

I tried this code:

from PIL import Image
import os
os.chdir('D:\\background')
img=os.listdir()
a=img.convert("P", palette=Image.ADAPTIVE, colors=8)
a.save('D:\\test')
 

So if I want to convert multiple files with pillow how should I do it?

1 Answers

Check documentation here https://pillow.readthedocs.io/en/stable/reference/Image.html

img=os.listdir(), and img is a list of filenames under the folder 'D:\background'. Here's my implementation:

from PIL import Image
import os

base_dir_src = 'D:\\background'
base_dir_dst = 'D:\\test'
os.chdir()
for filename in os.listdir():
    with Image.open(filename) as img:
        converted_img = img.convert("P", palette=Image.ADAPTIVE, colors=8)
        converted_img.save(os.path.join(base_dir_dst, filename))
Related