Python图片裁剪(如: 头像裁剪)
2017-06-18 本文已影响3324人
HiWoo
今天就来说个常用的功能,图片裁剪,可用于头像裁剪啊之类的。用的还是我们之前用的哪个模块pillow
不过最好还是客户端裁剪,这里只是为了讲一下图片处理的这个功能
1. 安装pillow####
用pip安装
pip install pillow
2. 图片裁剪####
2.1 准备一张图片

2.2 我们使用的是Image中的crop(box)功能,它需要一个参数box,元组 类型,元组包括4个元素,如:
(距离图片左边界距离x, 距离图片上边界距离y,距离图片左边界距离+裁剪框宽度x+w,距离图片上边界距离+裁剪框高度y+h)
如图:(x, y, x+w, y+h), x,y是裁剪框左上角的坐标, x+w,y+h是右下角的坐标

2.3 上代码1-裁剪:
# -*-coding:utf-8-*-
from PIL import Image
im = Image.open("renren.jpeg")
# 图片的宽度和高度
img_size = im.size
print("图片宽度和高度分别是{}".format(img_size))
'''
裁剪:传入一个元组作为参数
元组里的元素分别是:(距离图片左边界距离x, 距离图片上边界距离y,距离图片左边界距离+裁剪框宽度x+w,距离图片上边界距离+裁剪框高度y+h)
'''
# 截取图片中一块宽和高都是250的
x = 100
y = 100
w = 250
h = 250
region = im.crop((x, y, x+w, y+h))
region.save("./crop_test1.jpeg")
# 截取图片中一块宽是250和高都是300的
x = 100
y = 100
w = 250
h = 300
region = im.crop((x, y, x+w, y+h))
region.save("./crop_test2.jpeg")
运行结果:
(venv) allenwoo@~/renren/code$ python test.py
图片宽度和高度分别是(500, 500)


2.4 上代码2-平均切割成4块:
# 把图片平均分成4块
# 第1块
w = img_size[0]/2.0
h = img_size[1]/2.0
x = 0
y = 0
region = im.crop((x, y, x+w, y+h))
region.save("./crop_average-1.jpeg")
# 第2块
x = w
y = h
region = im.crop((x, y, x+w, y+h))
region.save("./crop_average-2.jpeg")
# 第3块
x = 0
y = h
region = im.crop((x, y, x+w, y+h))
region.save("./crop_average-3.jpeg")
# 第4块
x = w
y = 0
region = im.crop((x, y, x+w, y+h))
region.save("./crop_average-4.jpeg")
****运行结果:****




2.5 上代码3-旋转图片:
# 旋转图片
# 左旋转45度
im = im.rotate(45)
im.save("./rotate-l45.jpeg")
# 右旋转30度
im = im.rotate(-30)
im.save("./rotate-r30.jpeg")
# 右旋转45度, 并裁剪一块
im = im.rotate(-30)
x = 50
y = 50
w = 150
h = 150
region = im.crop((x, y, x+w, y+h))
region.save("./rotate-r30-crop.jpeg")
****运行结果:****



好了,到这里你完全可以做个头像裁剪了的后端操作了。