Section 158.1:读取图像文件

from PIL import Image
im = Image.open("Image.bmp")
  • 使用PIL.Image.open()方法打开图像文件。
  • im是一个Image对象,可以用于进一步处理图像。

Section 158.2:将文件转换为JPEG格式

from __future__ import print_function
import os, sys
from PIL import Image

for infile in sys.argv[1:]:
    f, e = os.path.splitext(infile)
    outfile = f + ".jpg"
    if infile != outfile:
        try:
            Image.open(infile).save(outfile)
        except IOError:
            print("cannot convert", infile)

命令行参数处理:

  • 使用sys.argv[1:]获取命令行中提供的文件路径列表。
  • os.path.splitext(infile)将文件名分割为文件名和扩展名。

文件名处理:

  • f是文件名(不包含扩展名),e是扩展名。
  • outfile是将文件名扩展名为.jpg的新文件名。

图像转换:

  • 使用Image.open(infile)打开输入文件。
  • 使用.save(outfile)将图像保存为JPEG格式。
  • 如果在转换过程中发生IOError,将打印错误信息。

示例运行

假设你有以下文件:

  • example1.png
  • example2.png

运行脚本:

python script.py example1.png example2.png

输出:

example1.jpg
example2.jpg

如果某个文件无法转换,将输出类似以下内容:

cannot convert example3.png
  1. 确保输入文件是有效的图像文件。
  2. 如果输入文件已经是JPEG格式,脚本不会进行转换。
  3. 如果需要处理大量文件,可以将文件路径存储在列表中,而不是通过命令行参数传递。