Pillow库支持多种图像格式,无论何种类型的图像,你都可以使用**open()**方法直接读取图像。同时,Pillow使得图像格式之间的转换变得非常容易。本文将告诉你如何使用python pillow转换图像格式。
1.Pillow提供了转换图像格式的方法。
- Pillow为我们提供了2个方法(save()&convert()) 来转换不同的图像格式。
- 我们将用例子逐一介绍。
1.1 save().
-
save()方法是用来保存图像的。当没有指定文件格式时,它将以默认的图像格式存储图像。如果指定了图像格式,图像将以指定的格式存储。
-
save()方法的语法如下:
Image.save(fp, format=None) -
fp:图片的保存路径,包括图片的名称,数值为字符串格式。
-
format: 指定图片的格式,这个参数是可选的。
-
在下面的例子中,我使用枕头模块的图像类的save()方法将源.tif图像文件转换为.png图像文件。
from PIL import Image def pillow_save_method_example(): # define the source image file path, the source image file is a .tif file. src_file_path = 'c:\\test.tif' # open the source image file with the pillow image class. image_object = Image.open(src_file_path) # define the target image file path. target_file_path = 'd:\\test-abc.png' # save the source image to the target image file, the target image file is a .png file. image_object.save(target_file_path) if __name__ == '__main__': pillow_save_method_example()
1.2 save() + convert()
-
不是所有的图像格式都可以用save()方法来转换。
-
例如,如果你像下面的源代码那样把PNG格式的图像保存为JPG格式的文件。
from PIL import Image src_file_path = 'd:\\test.png' target_file_path = 'd:\\test.jpg' image_object = Image.open(src_file_path) image_object.save(target_file_path) -
当你直接使用save()方法时,会出现以下错误。
Traceback (most recent call last): File "C:\Users\Jerry\anaconda3\Lib\site-packages\PIL\JpegImagePlugin.py", line 611, in _save rawmode = RAWMODE[im.mode] KeyError: 'RGBA' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "D:\Work\dev2qa.com-example-code\PythonExampleProject\com\dev2qa\example\code_learner_dot_com_example\pillow_example.py", line 94, in <module> pillow_save_method_example() File "D:\Work\dev2qa.com-example-code\PythonExampleProject\com\dev2qa\example\code_learner_dot_com_example\pillow_example.py", line 88, in pillow_save_method_example image_object.save(target_file_path) File "C:\Users\Jerry\anaconda3\Lib\site-packages\PIL\Image.py", line 2151, in save save_handler(self, fp, filename) File "C:\Users\Jerry\anaconda3\Lib\site-packages\PIL\JpegImagePlugin.py", line 613, in _save raise OSError(f"cannot write mode {im.mode} as JPEG") from e OSError: cannot write mode RGBA as JPEG -
该错误是由PNG和JPG图像模式的不一致引起的。
-
PNG是一种4通道的RGBA模式,即红、绿、蓝和Alpha透明色,JPG是一种三通道的RGB模式。
-
因此,如果你想实现图像格式的转换,你需要将PNG转换成三通道的RGB模式。
-
图像类提供了转换()方法来转换图像模式。这个函数提供了多个参数,如模式、矩阵、抖动等等。
-
最关键的参数是模式,其他参数不需要关注。以下是该方法的语法。
convert(mode,parms**) -
mode:指的是要转换的图像模式。
-
params:其他可选参数。
-
所以你可以把源代码改成下面的样子,以避免错误,只需要增加一行转换代码,把PNG图像模式从RGB转换为RGB。
```
from PIL import Image
# define the source and the target image file path.
src_file_path = 'd:\\test.png'
target_file_path = 'd:\\test.jpg'
# open the source image file.
image_object = Image.open(src_file_path)
# convert the source file PNG format file mode from RGBA to RGB and return a new Image object.
image_object1=image_object.convert('RGB')
# save the new mode Image object to the target JPG format file.
image_object1.save(target_file_path)
```