Pillow
PIL:Python Imaging Library,Python事实上的图像处理标准库
由于PIL仅支持到Python 2.X,于是有了Pillow,Pillow支持Python 3.X
Pillow能干啥
- 1.图像归档
- 2.图像显示
- 3.图像处理
安装Pillow
$ pip install pillow
操作图像
- 打开文件
from PIL import Image
im = Image.open(filename)
print(im.format, im.size, im.mode)
输出
JPEG (8256, 5504) RGB
- 截图
from PIL import Image
im = Image.open(filename)
box = (3000, 0, 5000, 2000)
region = im.crop(box)
region.save(filename.replace('.', '_crop.'))
效果图
- 区域旋转
from PIL import Image
im = Image.open(filename)
box = (3000, 0, 5000, 2000)
region = im.crop(box)
region = region.transpose(Image.ROTATE_180)
im.paste(region, box)
im.save(filename.replace('.', '_tp.'))
效果图
- 压缩:
from PIL import Image
# 打开图像文件
im = Image.open(filename)
# 获得图像尺寸:
w, h = im.size
# 缩放:
im.thumbnail((min(150, w), min(150, h)))
# 保存为jpeg格式
im.save(filename.replace('.', '_thumbnail.'))
效果图
- 模糊
from PIL import Image, ImageFilter
im = Image.open('test.jpg')
# 应用模糊滤镜
im2 = im.filter(ImageFilter.BLUR)
im2.save('test_blur.jpg', 'jpeg')
效果图
- 随机验证码生成
import random
from PIL import Image, ImageDraw, ImageFont, ImageFilter
def any_char():
return random.choice('ABCDEFG')
def any_color_light():
# 浅色
return (
random.randint(64, 255),
random.randint(64, 255),
random.randint(64, 255)
)
def any_color_dark():
# 深色
return (
random.randint(32, 127),
random.randint(32, 127),
random.randint(32, 127)
)
width, height = 60 * 4, 60
font = ImageFont.truetype('Arial.ttf', 36)
image = Image.new('RGB', (width, height), (255, 255, 255))
draw = ImageDraw.Draw(image)
# 浅色像素填充
for x in range(width):
for y in range(height):
draw.point((x, y), fill=any_color_light())
# 文字深色绘制
for t in range(4):
draw.text((60 * t + 10, 10), any_char(), font=font, fill=any_color_dark())
# 模糊保存
image = image.filter(ImageFilter.BLUR)
image.save(filename, 'jpeg')
效果图
更多功能
要详细了解PIL的强大功能,请请参考Pillow官方文档:
https://pillow.readthedocs.org/
网友评论