[英]Converting multiple files from JPG to PNG
I'm trying to convert multiple JPG files into PNG files.我正在尝试将多个 JPG 文件转换为 PNG 文件。 I'm able to do it for a single file but the loop doesn't seem to work for multiple files.我可以为单个文件执行此操作,但循环似乎不适用于多个文件。 Could you please help with that?你能帮忙吗? I'm sharing my code below:我在下面分享我的代码:
from PIL import Image
img = Image.open('./image.jpg')
img.save('new_image.png','png')
print('All done!')
You can try this -你可以试试这个——
from PIL import Image
import glob
counter = 0
for image in glob.glob("./*.jpg"):
counter = counter + 1
img = Image.open(image)
img.save(str(counter)+'new_image.png','png')
#So the following code worked. #所以下面的代码有效。 Sorry for the formatting, I'm just beginning to learn!抱歉格式化,我才刚开始学习!
from PIL import Image import glob import os从 PIL 导入图像导入 glob 导入操作系统
directory = r'C:\Users\Umar Iqbal\Desktop\newfolder' #this is where we will save our converted images directory = r'C:\Users\Umar Iqbal\Desktop\newfolder' #这是我们将保存转换后的图像的地方
for image in glob.glob('./*.jpg'): img = Image.open(image)对于 glob.glob('./*.jpg') 中的图像: img = Image.open(image)
clean_name = os.path.splitext(image)[0] #if we don't use this, we get jpg in the file's name clean_name = os.path.splitext(image)[0] #如果我们不使用这个,我们在文件名中得到jpg
img.save(f'{directory}{clean_name}.png', 'png') #this allows us to save the new images in the directory img.save(f'{directory}{clean_name}.png', 'png') #这允许我们将新图像保存在目录中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.