pillow包使用之图片裁剪

如果系统中没有安装pillow包,安装:

pip install pillow

修改图片的大小

'''
author: Angus Cai
Date: 2018-3-28
'''
import os
import os.path
from PIL import Image
'''
filein: 输入图片
fileout: 输出图片
width: 输出图片宽度
height:输出图片高度
type:输出图片类型(png, gif, jpeg...)
'''

def ResizeImage(filein, fileout, width, height, type):
	img = Image.open(filein)
	out = img.resize((width, height),Image.ANTIALIAS) #resize image with high-quality
	out.save(fileout, type)
if __name__ == "__main__":
	list = os.listdir("./")
	for i in range(0, len(list)):
		imgName = os.path.basename(list[i])
		if (os.path.splitext(imgName)[1] != ".jpg"): continue
		print(imgName)
		filein = imgName
		fileout = '%s'%imgName
		width = 64
		height = 64
		type = 'jpeg'
		ResizeImage(filein, fileout, width, height, type)

裁剪图片某个部分

裁剪左上角

# 导入pillow
from PIL import Image
 
# 加载原始图片
img = Image.open("lena.jpg")
 
# 从左上角开始 剪切 200*200的图片
img2 = img.crop((0, 0, 200, 200))
img2.save("lena2.jpg")

裁剪右下角

# 导入pillow
from PIL import Image
 
# 加载原始图片
img = Image.open("lena.jpg")
# img.size返回图片的大小元组,list()函数将元组转换成列表
width = list(img.size)[0]  # 图片大小
height = list(img.size)[1]
img3 = img.crop(
    (
        width - 200,
        height - 200,
        width,
        height
    )
)
img3.save("lena3.jpg")

裁剪中间部分

# 导入pillow
from PIL import Image
 
# 加载原始图片
img = Image.open("lena.jpg")
# img.size返回图片的大小元组,list()函数将元组转换成列表
width = list(img.size)[0]  # 图片大小
height = list(img.size)[1]
half_the_width = weight / 2
half_the_height = height / 2
img4 = img.crop(
    (
        half_the_width - 50,
        half_the_height - 75,
        half_the_width + 50,
        half_the_height + 75
    )
)
img4.save("lena4.jpg")

填充

longer_side = max(img4.size)
horizontal_padding = (longer_side - img4.size[0]) / 2
vertical_padding = (longer_side - img4.size[1]) / 2
img5 = img4.crop(
    (
        -horizontal_padding,
        -vertical_padding,
        img4.size[0] + horizontal_padding,
        img4.size[1] + vertical_padding
    )
)
img5.save("lena5.jpg")