# encoding: utf-8 # 随机码生成示例 import random import os from PIL import Image from PIL import ImageDraw from PIL import ImageFont def createcode(): """ 生成随机码 :return: 5位数随机码 """ s = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' code = '' for i in range(5): c = s[int(random.random() * len(s))] code += c return code def createcodeimg(code, path): """ 生成随机码图片 :param code: 随机码 :param path: 保存路径 :return: """ xoffset = 0 yoffset = 0 space = 20 img = Image.new('RGB', (0, 0), 'gray') font = ImageFont.truetype("hyzsf.TTF", 100) # 计算随机码长度 size = font.getsize(code) w = size[0] + space * (len(code) + 1) newsize = (w, size[1] + space * 2) # 重置图片大小 img = img.resize(newsize) # 计算纵向偏移,使纵向居中(不完全居中) yoffset = (newsize[1] - size[1]) / 2 imgdraw = ImageDraw.Draw(img) # 随机生成颜色 def randomcolor(): """ 随机生成颜色 :return: 32位颜色 """ color = 0 for i in range(3): color = (color << 8) | (int(random.random() * 0xff)) color = (0xff << 24) | color # print '0x%x' % color return color # 随机生成位置 def randomxy(): """ 基于图片的尺寸随机生成位置 :return: 位置tuple """ x = int(random.random() * newsize[0]) y = int(random.random() * newsize[1]) return (x, y) # draw lines for i in range(10): color = randomcolor() imgdraw.line([randomxy(), randomxy()], fill=color, width=2) # draw dots for i in range(50): xy = randomxy() radius = 2 xy2 = (xy[0] + radius * 2, xy[1] + radius * 2) imgdraw.ellipse([xy, xy2], randomcolor()) # draw code lastdirection = None for c in code: size = font.getsize(c) w, h = size[0], size[1] r = max(w, h) imgtmp = Image.new('RGBA', (r, r), 0) imgdrawtmp = ImageDraw.Draw(imgtmp) imgdrawtmp.text(((r - w) / 2, (r - h) / 2), c, fill=randomcolor(), font=font) direction = 1 if random.random() > 0.5 else -1 #调整旋转方向 if lastdirection == direction: lastdirection = direction = -direction rotate = direction * (10 + random.random() * 45) # 旋转 imgtmp = imgtmp.rotate(rotate) imgdraw.bitmap((xoffset, yoffset), imgtmp, fill=randomcolor()) xoffset += (w + space) # 保存到 img.save(path) if not os.path.exists('../img/code'): os.makedirs('../img/code') for i in range(100): # code = u'hello中国' code = createcode() createcodeimg(code, '../img/code/%d.jpg' % i)
Python-生成随机码图片
最新推荐文章于 2023-02-10 15:07:48 发布