【发布时间】:2020-12-18 06:58:38
【问题描述】:
我正在编写一个脚本来浏览一个装满图片的文件夹并做两件事。出于这个问题的目的,我只关注第一个。
这是将任何 .png 文件转换为 .jpg。
脚本如下
from PIL import Image
import os,sys
# Check if a filepath was provided
if len(sys.argv)!=2:
print("Please enter one filepath")
sys.exit(1)
else:
directory=sys.argv[1]
number_pictures=0
number_errors=0
# converts any non .jpg file into a .jpg
def convert_to_jpg():
name,ext = os.path.splitext(full_path)
new_file_name=name+".jpg"
try:
with Image.open(full_path) as image:
image.save(new_file_name)
except OSError:
print("ERROR!\nUnable to convert file: "+new_file_name)
def resizeImage():
print("Hello")
# Iterates through the folder and calls the appropriate method/s based
# on certain characteristics.
for root, dirs, files in os.walk(directory,topdown=True,followlinks=False):
for file in files:
if file.endswith('.png'):
full_path=root+file
convert_to_jpg()
number_pictures+=1
print(str(number_pictures))
请忽略 resizeImage 函数,因为它显然还没有准备好。
脚本(大部分)工作并且确实遍历文件路径中给出的文件。它确实尝试将文件夹中的每个文件转换为 .jpg,但正如您在下面的图片中看到的那样,似乎只有大约一半的文件正确转换。
如您所见,我的测试文件夹包含 10 张不同名称的 .png 图片。有些有空格,有些全小写,还有一些大写。
您可以在此处看到已处理的 9 个文件(仍在找出未处理该文件的原因)中有 5 个返回错误。
图片文件夹中的结果是 9 个新文件(Capture.png 文件未处理),其中只有 4 个可以正常工作。带有绿色占位符图标的 .jpg 文件返回元数据错误。
似乎没有任何韵律或原因导致图片无法正常工作,而且我对文件转换过程背后的过程了解得不够多,无法猜测发生了什么。
任何帮助将不胜感激!
【问题讨论】:
-
@MarkSetchell 那是一本非常好的、内容丰富的读物。我对我的代码进行了一次调整,它现在可以正常工作了!谢谢!
标签: python python-imaging-library image-conversion