框架:PIL,Django
效果:
源码:
from PIL import Image, ImageDraw, ImageFont
import random
from django.http import HttpResponse
from io import BytesIO
def get_random_color():
color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
return color
def verification_code(request):
width = 200
height = 50
background_color = get_random_color()
image = Image.new('RGB', (width, height), background_color)
draw = ImageDraw.Draw(image)
for i in range(0, 100):
xy = (random.randrange(0, width), random.randrange(0, height))
draw.point(xy, fill=get_random_color())
for i in range(0, 10):
xy_start = (random.randrange(0, width), random.randrange(0, height))
xy_end = (random.randrange(0, width), random.randrange(0, height))
draw.line((xy_start, xy_end), fill=get_random_color())
rand_python = ''
for i in range(4):
random_number = str(random.randint(0, 9))
random_lower_letter = chr(random.randint(97, 122))
random_upper_letter = chr(random.randint(65, 90))
rand_python += random.choice([random_number, random_lower_letter, random_upper_letter,])
color = get_random_color()
text_color = [0, 0, 0]
for j in range(2):
if color[j]-background_color[j] <= 30:
text_color[j] = 255-color[j]
else:
text_color[j] = color[j]
draw.text((i * (width/4) + 10, 2),
rand_python[i],
tuple(text_color),
font=ImageFont.truetype(r'C:\Windows\Fonts\BRADHITC.TTF', 40),
align='center')
del draw
request.session['verification_code'] = rand_python
buf = BytesIO()
image.save(buf, 'png')
return HttpResponse(buf.getvalue(), 'image/png')