[英]Converting all files (.jpg to .png) from a directory in Python
I'm trying to convert all files from a directory from .jpg to .png.我正在尝试将目录中的所有文件从 .jpg 转换为 .png。 The name should remain the same, just the format would change.
名称应该保持不变,只是格式会改变。
I've been doing some researches and came to this:我一直在做一些研究并得出以下结论:
from PIL import Image
import os
directory = r'D:\PATH'
for filename in os.listdir(directory):
if filename.endswith(".jpg"):
im = Image.open(filename)
im.save('img11.png')
print(os.path.join(directory, filename))
continue
else:
continue
I was expecting the loop to go through all my .jpg files and convert them to .png files.我期待循环遍历我所有的 .jpg 文件并将它们转换为 .png 文件。 So far I was doing only with 1 name: 'img11.png', I haven't succed to build something able to write the adequate names.
到目前为止,我只使用了 1 个名称:'img11.png',我还没有成功构建出能够写出足够名称的东西。
The print(os.path.join(directory, filename))
works, it prints all my files but concerning the converting part, it only works for 1 file. print(os.path.join(directory, filename))
工作,它打印我所有的文件,但关于转换部分,它只适用于 1 个文件。
Do you guys have any idea for helping me going through the process?你们有什么想法可以帮助我完成整个过程吗?
You can convert the opened image as RGB and then you can save it in any format.您可以将打开的图像转换为 RGB,然后您可以将其保存为任何格式。 You can try the following code :
您可以尝试以下代码:
from PIL import Image
import os
directory = r'D:\PATH'
c=1
for filename in os.listdir(directory):
if filename.endswith(".jpg"):
im = Image.open(filename)
name='img'+str(c)+'.png'
rgb_im = im.convert('RGB')
rgb_im.save(name)
c+=1
print(os.path.join(directory, filename))
continue
else:
continue
You're explicitly saving every file as img11.png
.您明确地将每个文件保存为
img11.png
。 You should get the name of your jpg
file and then use that to name and save the png
file.您应该获取
jpg
文件的名称,然后使用它来命名和保存png
文件。
name = filename[:-4]
im.save(name + '.png')
I would have used os.rename() function like below.我会使用 os.rename() 函数,如下所示。
import os
directory = r'D:\PATH'
for filename in os.listdir(directory):
prefix = filename.split(".jpg")[0]
os.rename(filename, prefix+".png")
Please let me know if this is what you wanted.请让我知道这是否是您想要的。 Try the code with some copied images inside a test folder, before applying to the intended folder.
在应用到预期文件夹之前,尝试在测试文件夹中复制一些图像的代码。 All the best.
祝一切顺利。
from PIL import Image
import os directory = r'D:\PATH'
for filename in os.listdir(directory):
if filename.endswith(".jpg"):
prefix = filename.split(".jpg")[0]
im = Image.open(filename)
im.save(prefix+'.png')
else:
continue
Please try this one and let me know.请试试这个,让我知道。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.