Lorenzo Benassi
Lorenzo Benassi

Reputation: 621

Convert image format in series with Python

sorry for my trivial question, but I'm new to Python.

I'm trying to convert a series of JPEG images to BMP format and resize it. I managed to get the procedure for a single image, but now I can not automate the process so that the conversion happens in sequence. this is my script

from PIL import Image
img = Image.open("C:/Users/***/Documents/images/1.jpg")
new_img = img.resize((320,240))
new_img.save("C:/Users/***/Documents/immages_bmp/1.bmp")

The images are progressively renamed from 1 to 10000. Does anyone know how to help me implement a for loop to automate the process? Thank you so much for your help

Upvotes: 0

Views: 1229

Answers (1)

Pam
Pam

Reputation: 1163

Something like:

from PIL import Image
from glob import glob
import os
myDir = '/Users/me/pictures'
pic_list = glob(myDir + os.sep + '*' + '.jpg')

for pic in pic_list:
  #resize, use a string replace to name new bmps
  img = Image.open(pic)
  new_img = img.resize((320,240))
  newName = pic.replace(".jpg",".bmp")
  new_img.save(newName)

Should catch all the images regardless as to their naming convention, and will allow you to edit the list of names before you resize them (or not).

Upvotes: 2

Related Questions