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

2024-04-26 02:27:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试制作一个脚本,根据从XML中提取的数据调整多个或单个图像的大小。 我的问题是,如果我有多个图像,我怎么能打印出一个像“有一个以上的图像,你想调整图像2的大小吗?。。。而不是“你是否也可以调整图片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)  

先谢谢你

札幌


Tags: pathin图像imageimportimgnewfor
1条回答
网友
1楼 · 发布于 2024-04-26 02:27:28

将最终循环更改为:

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

相关问题 更多 >

    热门问题