程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python generates image verification code through pil

編輯:Python
# -- coding: utf-8 --
Import three modules
import Image,ImageDraw,ImageFont
import random
import math
''' Basic function '''
Image width
width = 100
Picture height
height = 40
The background color
bgcolor = (255,255,255)
Generate background picture
image = Image.new('RGB',(width,height),bgcolor)
Load Fonts
font = ImageFont.truetype('FreeSans.ttf',30)
The font color
fontcolor = (0,0,0)
produce draw object ,draw Is a collection of algorithms
draw = ImageDraw.Draw(image)
Draw Fonts ,(0,0) It's the starting position
draw.text((0,0),'1234',font=font,fill=fontcolor)
Release draw
del draw
Save the original version
image.save('1234_1.jpeg')
''' Demo twist , You need to create a new picture object '''
New picture
newImage = Image.new('RGB',(width,height),bgcolor)
load Pixels
newPix = newImage.load()
pix = image.load()
offset = 0
for y in range(0,height):
offset += 1
for x in range(0,width):
# new x Coordinates
newx = x + offset
# You can try the following effects
#newx = x + math.sin(float(y)/10)*10
if newx < width:
# Shift the source pixel to a new pixel by
newPix[newx,y] = pix[x,y]
Save the distorted version
newImage.save('1234_2.jpeg')
''' Change the shape '''
x1 = ax+by+c
y1 = dx+ey+f
newImage = image.transform((width+30,height+10), Image.AFFINE, (1,-0.3,0,-0.1,1,0))
newImage.save('1234_3.jpeg')
''' Drew interference , Don't draw too much , So that users can't see clearly '''
establish draw, For drawing lines
draw = ImageDraw.Draw(newImage)
Line color
linecolor= (0,0,0)
for i in range(0,15):
# It's all random
x1 = random.randint(0,width)
x2 = random.randint(0,width)
y1 = random.randint(0,height)
y2 = random.randint(0,height)
draw.line([(x1, y1), (x2, y2)], linecolor)
Save to local
newImage.save('1234_4.jpeg')</pre> 

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved