Search code examples
pythonfor-looppython-imaging-libraryjpegbmp

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


Solution

  • 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).