Python调整大小多个图像要求用户继续

时间:2015-06-15 11:34:33

标签: python xml image resize

我试图制作一个脚本,根据从XML中提取的数据调整多个或单个图像的大小。 我的问题是,如果我有多个图像,我怎么能打印出像#34这样的问题;你想要调整图像2的图像有多于1个图像?...而不是"你是否还要调整图像3的大小?"

我的脚本到目前为止如下,唯一的问题是它在开始时调整所有图像的大小:

import os, glob
import sys 
import xml.etree.cElementTree as ET 
import re 
from PIL import Image

pathNow ='C:\\' 


items = []
textPath = []
imgPath = []

attribValue = []

#append system argument to list for later use

for item in sys.argv: 
    items.append(item)

#change path directory 
newPath = pathNow + items[1]  
os.chdir(newPath) 
#end 

#get first agrument for doc ref
for item in items:
    docxml = items[2]

#search for file 
for file in glob.glob(docxml + ".xml"): 
    tree = ET.parse(file) 
    rootFile = tree.getroot() 
    for rootChild in rootFile.iter('TextElement'):
        if "svg" or "pdf" in rootChild.text:
            try:
                textPath = re.search('svg="(.+?)"', str(rootChild.text)).group(1)
                attribValue.append(rootChild.get('elementId'))
                imgPath.append(textPath)
            except:
                continue

for image in imgPath:
    new_img_path = image[:-4] + '.png'
    new_image = Image.open(new_img_path)
    new_size=int(sys.argv[3]), int(sys.argv[4])
    try:
        new_image.thumbnail(new_size,  Image.ANTIALIAS)
        new_image.save(new_img_path, 'png')
    except IOError:
        print("Cannot resize picture '%s'" % new_img_path)
    finally:
        new_image.close()
        print("Done resizeing image: %s " % new_img_path)  

提前谢谢。

ZAPO

1 个答案:

答案 0 :(得分:1)

将最终循环更改为:

for idx, image in enumerate(imgPath):
    #img resizing goes here

    count_remaining = len(imgPath) - (idx+1)
    if count_remaining > 0:
        print("There are {} images left to resize.".format(count_remaining))
        response = input("Resize image #{}? (Y/N)".format(idx+2))
        #use `raw_input` in place of `input` for Python 2.7 and below
        if response.lower() != "y":
            break