【发布时间】:2021-04-23 21:29:25
【问题描述】:
我有一个程序应该将图像转换为具有透明边框的方形 png(如果图像为 1000x1500,则 png 为 1500x1500,然后图像将放置在 png 的中间,创建透明边框250x1500 两侧)。该程序应该从我可以选择要从中导入的文件夹中导入图像,然后将其导出到您也可以选择的另一个文件夹中。我使用递归从文件夹中抛出所有图像,但是它说输入无法识别。谁能帮我解决这个问题?在我现在发送的代码中,你有你需要解释的一切:
from PIL import Image
from os import listdir
from os.path import isfile, join,splitext
Folder_Input = 'D:\\0Pi_\Downloads\ScpServer\Originais' #directory where we will upload images
Folder_Output ='D:\\0Pi_\Downloads\ScpServer\PNGs' #directory where we will save images
typelist = ['.png','.jpg','.jpeg']
images_list = [f for f in listdir(Folder_Input) if isfile(join(Folder_Input, f)) and splitext(f)[1].lower() in typelist]
for im in images_list:
try:
image = Image.open(im) #this is supposed to open the image, however it doesn't. what's missing
except:
print(f'Problem opening image{im}!\n')
image.close()
continue
width, height = image.size
if height >= width:
new_width = height
new_height = height
else:
new_width = width
new_height = width
result = Image.new(mode = 'RGBA', size = (new_width, new_height) ,color = (0,0,0,0)) #creates a new transparent squared png
offset = ((new_width - width) // 2, (new_height - height) // 2) #centers the image in relation to the squared png
result.paste(image,offset) #unites both the image and the squared layer
image.close() #closes the file now finished
output_file = join(Folder_Output,splitext(im)[0] + '.png')
if not isfile(output_file):
result.save(output_file) #saves file on the output folder
else:
print(f"The file {splitext(im)[0] + '.png'} was not saved because it already exists on {Folder_Output}!\n")
这是 Tracebak:
Traceback (most recent call last):
File "D:/0Pi_/Documents/add_borders.py", line 16, in <module>
image.close()
builtins.NameError: name 'image' is not defined
【问题讨论】:
-
它在哪里说的?你有错误吗?完整的追溯是什么?
-
我忘了补充。我编辑了我的帖子,它现在在结尾
-
这能回答你的问题吗? Can't Open files from a directory in python
标签: python python-imaging-library