Python PIL库介绍与基本操作

Python PIL库介绍与基本操作

Python PIL库介绍与基本操作

Python Imaging Library(PIL)是一个Python图像处理库,它提供了强大而灵活的图像处理功能,能够加载、显示、保存和处理各种图像格式。在本文中,我们将介绍PIL库的基本用法和常见操作,帮助读者快速上手图像处理。

安装PIL库

在使用PIL之前,首先需要安装PIL库。可以使用pip命令来安装PIL库:

pip install pillow
Bash

导入PIL库

安装完成后,我们可以在Python脚本中导入PIL库:

from PIL import Image
Python

打开和显示图像

PIL库可以打开各种图像格式的文件,比如JPEG、PNG、BMP等。下面是一个简单的示例代码,用于打开并显示一张图片:

from PIL import Image

img = Image.open('example.jpg')
img.show()
Python

在这个示例中,我们使用Image.open()方法打开一张名为example.jpg的图片,然后使用img.show()方法显示该图片。

图像基本操作

获取图像尺寸

可以使用Image.size属性获取图像的尺寸,返回一个元组,包含图像的宽度和高度。下面是一个示例代码:

from PIL import Image

img = Image.open('example.jpg')
width, height = img.size

print(f'图像尺寸为:{width} x {height}')
Python

运行结果:

图像尺寸为:800 x 600
Python

调整图像尺寸

可以使用Image.resize()方法调整图像的尺寸。下面是一个示例代码,将图像尺寸调整为200×200:

from PIL import Image

img = Image.open('example.jpg')
resized_img = img.resize((200, 200))

resized_img.show()
Python

旋转图像

可以使用Image.rotate()方法将图像旋转指定角度。下面是一个示例代码,将图像顺时针旋转90度:

from PIL import Image

img = Image.open('example.jpg')
rotated_img = img.rotate(90)

rotated_img.show()
Python

图像剪切

可以使用Image.crop()方法对图像进行剪切操作。下面是一个示例代码,将图像剪切为左上角100×100的区域:

from PIL import Image

img = Image.open('example.jpg')
cropped_img = img.crop((0, 0, 100, 100))

cropped_img.show()
Python

图像保存

可以使用Image.save()方法将图像保存为指定格式的文件。下面是一个示例代码,将图像保存为PNG格式:

from PIL import Image

img = Image.open('example.jpg')
img.save('output.png', format='PNG')
Python

总结

本文介绍了Python PIL库的基本用法和常见操作,包括打开和显示图像、获取图像尺寸、调整图像尺寸、旋转图像、图像剪切以及图像保存等操作。读者可以根据这些操作开始进行图像处理,进一步探索PIL库的更多功能。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册