Python例子-图片验证码
代码实现如下:
class ImageCodeView(View):
def get(self,request):
im = Image.new('RGB', (125, 50)) # 图片大小
draw = ImageDraw.Draw(im)
font = ImageFont.truetype(settings.BASE_DIR+'/html/static/simhei.ttf', 55) # 字体位置,字体大小
def random_color1():
"""随机颜色1(用于填充字体)"""
return random.randint(10, 80), random.randint(10, 80), random.randint(10, 80)
def random_color2():
"""随即颜色2(用于填充背景)"""
return random.randint(100, 255), random.randint(100, 255), random.randint(100, 255)
for x in range(125):
for y in range(50):
draw.point((x, y), fill=random_color2()) # 对每个像素点进行填充
draw.text((10, -2), 'ABCD', font=font,fill=random_color1()) # 10左偏移位置,0上偏移位置
out = BytesIO()
im.save(out, format='png') # 保存为PNG图片
# out.getvalue()图片的二进制,返回前端游览器
return HttpResponse(out.getvalue(),content_type='image/png')
安卓学习教程公众号

赏
微信打赏

祝你事业顺心,富贵吉祥,赞赏鼓励