Pillow
Python平台的图像处理标准库
获取图片大小
运行示例
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Python基础 Pillow
from PIL import Image
def getSize():
# 打开一个图片
pic = Image.open("D:/PythonProject/test.jpg")
# 获取图片大小
w, h = pic.size
print("原始图片大小 %s x %s" %(w,h))
getSize()
运行结果
D:\PythonProject>python main.py
原始图片大小 5184 x 3456
缩放图片
运行示例
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Python基础 Pillow
from PIL import Image
# 缩放图片
def thumbnail():
# 打开一个图片
pic = Image.open("D:/PythonProject/test.jpg")
# 获取图片大小
w, h = pic.size
print("原始图片大小 %s x %s" %(w,h))
# 缩放一半
pic.thumbnail((w//2, h//2))
newW, newH = pic.size
print("缩放后的图片大小 %s x %s" %(newW,newH))
# 另存图片
pic.save("thumbnail_test.jpg", "jpeg")
thumbnail()
运行结果
D:\PythonProject>python main.py
原始图片大小 5184 x 3456
缩放后的图片大小 2592 x 1728
模糊特效
运行示例
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Python基础 Pillow
from PIL import Image, ImageFilter
# 模糊特效
def imageBlur():
# 打开一个图片
pic = Image.open("D:/PythonProject/chen.jpg")
# 加模糊滤镜
newPic = pic.filter(ImageFilter.BLUR)
newPic.save("blur_chen.jpg", "jpeg")
imageBlur()
验证码
运行示例
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Python基础 Pillow
from PIL import Image, ImageFilter, ImageDraw, ImageFont
import random
# 随机字母
def randomChar():
return chr(random.randint(65, 90))
# 随机颜色
def randomColor():
return (random.randint(64, 255),random.randint(64, 255),random.randint(64, 255))
# 文字颜色
def rndFontColor():
return (random.randint(32, 127), random.randint(32, 127), random.randint(32, 127))
# 图片大小
width = 60 * 5
height = 60
pic = Image.new("RGB", (width, height),(255,255,255))
# 创建画笔
font = ImageFont.truetype('arial.ttf', 36)
# 创建Draw对象
draw = ImageDraw.Draw(pic)
# 填充每个像素
for x in range(width):
for y in range(height):
draw.point((x, y), fill = randomColor())
# 文字
for t in range(5):
draw.text((60 * t + 10, 10), randomChar(), font=font, fill=rndFontColor())
pic.save("code.jpg", "jpeg")
运行结果