Python编程:pillow处理图像生成验证码图片
2023-09-14 09:07:14 时间
安装
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套接字编程基础
- python异常处理与上下文管理器
- python-一个小练习
- 查看python对象的属性
- Python实现比较两个列表(list)范围
- Python网络编程之TCP套接字简单用法示例
- 【python】函数式编程
- python_并发编程初探(进程篇)
- python_面向对象高级——元类
- Python在数据分析中的作用,一文带你了解Python,学习Python
- 蚂蚁群算法求解最短路径问题(Python&Matlab实现)
- python居然还能画出这么精美的魔法少女,惊我一整年
- 【华为机试真题 Python实现】股票最大收益
- Python编程:列表List.sort和sorted方法排序
- Python编程:Counter计数器-dict字典的子类
- 【leetcode】sort list(python)
- Python获取prometheus监控和告警数据
- for循环中的lambda与闭包——Python的闭包是 迟绑定 , 这意味着闭包中用到的变量的值,是在内部函数被调用时查询
- Python少儿编程入门篇(8)数的进制和按位运算符