Simple use of the PIL library

The image processing library PIL (Python Imaging Library) in Python is widely used, so here is a brief introduction and use.

Install

It can pip install PILbe installed by, and I won't say more here.

use

load image

To be able to load the image we want to use from the file, the open() function under the Image module in the PIL library should be called:

from PIL import Image
img = Image.open("test.jpg")

If the loading is successful, then at this time we can get some attributes of the image from img :

print img.format, img.size, img.mode

You will get an output similar to JPEG (640, 640) RGBthis, which proves that the image has been successfully loaded.

If the image fails to load successfully, the format attribute of img is set to None; the size attribute is a two-tuple, which contains the width and height in pixel units of the image; the mode attribute defines the number and name of the bands in the image, as well as the pixel type and depth. If the image cannot be opened, the IOError method will be called.

When all the above are true, we have already got an instance img , through img.show()which we can display the picture.

Manipulate images

With this library, we can scale images with only three or four lines of code:

from PIL import Image

# 打开图像文件
img = Image.open('test.jpg')
# 获得图像尺寸:
width, height = img.size
# 缩放到原图的50%
im.thumbnail((w//2, h//2))
# 把缩放后的图像用jpeg格式保存:
im.save('thumbnail.jpg', 'jpeg')

The ImageDraw model under the PIL library also provides a variety of drawing methods, which can be read and used by yourself through the official documentation , and will not be described here due to time constraints.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325383707&siteId=291194637