安装

pip install pillow

缩略图

from PIL import Image

def thumbnail(image_path, save_path, scale=2):
img = Image.open(image_path)
# 图片尺寸
w, h = img.size
# 缩放图片
img.thumbnail((w//scale, h//scale))
# 保存
img.save(save_path, 'jpeg')

模糊效果

from PIL import Image

def filter(image_path, save_path):
img = Image.open(image_path)
img2 = img.filter(ImageFilter.BLUR)
img2.save(save_path, 'jpeg')

生成字母验证码图片

import random
import string
from PIL import Image, ImageFilter, ImageFont, ImageDraw

# 获取一个字母或数字
def get_char():
return random.choice(string.ascii_letters + string.digits)

# 获取颜色值
def get_color1():
return (random.randint(64, 255), random.randint(64, 255), random.randint(64, 255))

def get_color2():
return (random.randint(32, 127), random.randint(32, 127), random.randint(32, 127))

# 生成字母验证码图片
def get_checkcode_image(n, save_path):
"""
@param n: {int} 字母数量
@param save_path: {str} 保存路径
@return: None
"""
# 图片尺寸
width = 60*n
height = 60

image = Image.new("RGB", (width, height), (255, 255, 255))
# 创建Font对象
font = ImageFont.truetype('Arial.ttf', 36)
# 创建Draw对象
draw = ImageDraw.Draw(image)

# 填充每个像素
for x in range(width):
for y in range(height):
draw.point((x, y), fill=get_color1())

# 输出文字
for i in range(n):
draw.text((60 * i + 10, 10), get_char(), font=font, fill=get_color2())

# 模糊处理
image = image.filter(ImageFilter.BLUR)

image.save(save_path, "jpeg", dpi=(300.0, 300.0))


if __name__ == '__main__':
image_path = "images/my_image.png"
save_path = "thumbnail.jpg"
thumbnail(image_path, save_path)
filter(image_path, "filter.jpg")
get_checkcode_image(4, "code.jpg")


参考
​廖雪峰python-pillow​