1.生成图片的模块pillow,在python中安装pillow,在Django中使用时用PIL
2. 在页面上<img >

2.后端处理

1.生成一个图片对象:from PIL import Image

   # 获取随机颜色的函数
    def get_random_color():
        return random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)
    def new(mode, size, color=0) 有三个参数
    img_obj=Image.new(
        'RGB',
        (220,35) 图片大小
         get_random_color() 返回的是元祖(2551522) 图片颜色
    )

2.生成的图片放在磁盘或加载到内存

1.将生成的图片保存到磁盘上:
    with open("s10.png","wb") as f:
        img_obj.save(f,"png")
    with open("s10.png","rb") as f:
        data=f.read()
2.将生成的图片在内存中加载
from io import BytesIO
io_obj=BytesIO()
# 将生成的图片数据保存在io对象中
img_obj.save(io_obj,'png')
# 从io对象里面取上一步保存的数据
data=io_obj.getvalue()
3.将生成的图片返回到页面
return HttpResponse(data)

3.在图片上添加文本

from PIL import Image, ImageDraw, ImageFont
draw_obj = ImageDraw.Draw(img_obj)  # 生成一个图片画笔对象
# # 加载字体文件, 得到一个字体对象,路径从项目的根目录下找
font_obj = ImageFont.truetype("static/font/kumo.ttf", 28)
##生成的字符串写到图片上draw_obj.text(x,y,l,m) x为写的位置,tmp写的文本,fill文本颜色,font文本字体
draw_obj.text((20 , 0), "python", fill=(5, 55, 4), font=font_obj)

4.验证码

 for i in range(6):
        u = chr(random.randint(65, 90))  # 生成大写字母
        m = chr(random.randint(97, 122)) # 生成小写字母
        l = random.randint(0, 9)
        tmp = random.choice([u, m, l])
        tmp_list += str(tmp)
    print(tmp_list)

5.加干扰先和干扰点

加干扰线
width = 220  # 图片宽度(防止越界)
height = 35
for i in range(5):
    x1 = random.randint(0, width)
    x2 = random.randint(0, width)
    y1 = random.randint(0, height)
    y2 = random.randint(0, height)
    draw_obj.line((x1, y1, x2, y2), fill=get_random_color())

# 加干扰点
for i in range(40):
    draw_obj.point((random.randint(0, width), random.randint(0, height)), fill=get_random_color())
    x = random.randint(0, width)
    y = random.randint(0, height)
    draw_obj.arc((x, y, x+4, y+4), 0, 90, fill=get_random_color())
View Code

相关文章: