将PNG图像从文件夹转换为JPG-Python

时间:2020-08-27 00:10:36

标签: python

有人可以告诉我如何将本地文件夹中的所有png图像转换为jpg图像吗?我尝试使用以下代码

path1 = r'C:\Users\david.han\Desktop\COPY_images_files' 

path2 = r'C:\Users\david.han\Desktop\JPG converter'

files_to_convert = (f for f in os.listdir(path1) if f.endswith(".png"))
for filename in files_to_convert:
    im = Image.open(os.path.join(path1, filename))
    root, _ = os.path.splitext(filename)
    jpg_file = os.path.join(path2, f'{root}.jpg')
    im.save(jpg_file)

我不断收到此错误“ OSError:无法将模式P写入JPEG”

1 个答案:

答案 0 :(得分:0)

我已决定保留JPG,但万一有人想知道如何将png更改为jpg

enter code here

from PIL import Image 
import os 

path = r'C:\Users\david.han\Desktop\COPY_images_files'

for file in os.listdir(path): 
    if file.endswith(".jpg"): 
        img = Image.open(file)
        file_name, file_ext = os.path.splitext(file)
        img.save('/png/{}.png'.format(file_name))