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")