【问题标题】:Convert JFIF files to JPEG in python在python中将JFIF文件转换为JPEG
【发布时间】:2022-09-25 01:48:35
【问题描述】:

我有一个包含 JFIF 照片的文件夹,我需要将它们全部转换为 JPEG 格式,我认为问题出在我的 if 语句中,因为文件夹中有其他照片不需要转换或 for 循环.谢谢

from PIL import Image
import os

root = r\"(my computer path to the folder)\"

count = 0
for dirs, subdir, files in os.walk(root):
    for file in files:
        lastChar = file[-1:]
        if(lastChar == \'f\'):
            img = Image.open(file)
            #file ends in .jfif, remove 4 characters
            fileName = file[:-4]
            #add jpg and save
            img.save(fileName + \"jpg\")

我现在收到此错误, FileNotFoundError:[Errno 2] 没有这样的文件或目录:\'IMG_4242_1615254307.jfif\'

  • img = Image.open(file) - 这将在 CWD 中查找 file,而不是在 dirs 文件夹中
  • @buran 我想知道glob 是否会更好地解决这个问题?
  • 我认为您可以将文件从.jfif 重命名为.jpg,而无需阅读它们、解压缩它们并重新压缩它们,并且可能会花费很长时间并降低质量。也许尝试重命名一个。

标签: python


【解决方案1】:
from PIL import Image
import os

root = r"my computer path to the folder"
print(root)
count = 0
for dirs, subdir, files in os.walk(root):
    for file in files:
        lastChar = file[-4:]
        if(lastChar == 'jfif'):
            img = Image.open(root+'\\'+file)
            #file ends in .jfif, remove 4 characters
            fileName = file[:-4]
            print(fileName)
            #add jpg and save
            img.save(root+'\\'+fileName + "jpg")

【讨论】:

  • 请编辑您的代码格式。此外,您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。
【解决方案2】:

我遇到了同样的问题。我的问题由this 解决。请记住,源目录必须包含根据此代码 sn-p 的子目录。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-28
    • 2012-12-22
    • 2014-06-25
    • 1970-01-01
    • 2019-10-17
    • 2020-03-13
    相关资源
    最近更新 更多