I've got a little app to resize and watermark images. At the moment it only does one at a time but I would like to get it to do a full folder of images in one go. I have done this previously in VB using loops but im new to python and can't seem to get it to work. The running bit of the code I have is below and "watermark" is a function that given the 3 parts overlays and saves the image.

def run():
    #define variables and loop here
    #jpeg load and save
    a = tkFileDialog.askopenfile()
    im = Image.open(a)
    b = tkFileDialog.askopenfile()
    mark = Image.open(b)
    c = tkFileDialog.askopenfile()
    mark2 = Image.open(c)
    watermark(im, mark, mark2).save('output.jpg', "JPEG", quality=100)

Im guessing at using a tkFileDialog.askdirectory() then setting a loop to run the watermark function on all the images in the directory. I will neew a way to save them all aswell, possibly a counter in the loop to name them output1.jpg output2.jpg ect.

Thanks in advance,

Rich

Here is some kind of skeleton to copy your files (you'll have to adapt it but the principle is here) :

import os, fnmatch, shutil
mydir="/path/to/my/dir/"
for filename in fnmatch.filter(os.listdir(mydir),'*.py'):
    shutil.copy(filename, "anotherDir/new-%s" % filename)

Note that if you want to explore the dir recursively, you can do:

for subdir, dirs, files in os.walk(mydir):
    for filename in files:
        shutil.copy(os.path.join(subdir, filename), "anotherDir/%s/new-%s" % (subdir.replace(mydir,""), filename)) # not tested but certainly close ;-)

You could also do it with just the os module.

I use a variation of the fallowing code to loop through a folder of pictures. But I set them as my background instead of formatting them.

Play around with it, but it should work.

import ctypes, time, os

p = "C:\Path\To\Picture\Folder"
os.chdir(p)


while 1:
  for i in os.listdir(os.getcwd()):
    im = Image.open(i)
    #do your resize and watermark thing.
    #be sure to close the image after saving.
    im.close()

Many thanks, I now have it working based around Tech B's solution. Only problem was the

while 1:

statement made it loop through the folder over and over (very quickly filling my HDD). Putting in a little count variable fixes this. I also found the

im.close()

part not necessary.

Here is my loop through a folder working code for the benefit of the searchers.

import Image,  os, tkFileDialog

def function(im):
    
    #write function task here

def run():
    p = tkFileDialog.askdirectory()
     
    os.chdir(p)   
    count = 0   
    while (count < 1):
      for i in os.listdir(os.getcwd()):
        count = count + 1
        #change im to different file type if required
        im = Image.open(i)
        function(im)
       
if __name__ == '__main__':
    run()

Thanks again guys!

Rich

This question has already been answered. Start a new discussion instead.