【Pythonプロジェクト実践】検証コード画像の生成
12275 ワード
基本的には、どのネットワークサービスを使用しても認証コードに遭遇します.一般的には、サイトが登録しやすく、投稿しにくいように設定した検証手段です.その生成原理は、ランダムに生成された数字や記号の列を1枚の画像に生成し、画像にいくつかのインターフェロンを加えてOCRを防止することである.認証コードの生成方法について詳しく説明します.
通常、Python環境のほかにPILライブラリが必要ですが、PILライブラリの役割は前のブログを参照してください.検証コードピクチャを生成する場合は、まず26文字の大文字と小文字、10文字のランダム文字列を生成します.次に画像を作成し、文字列を書き込むには、この中のフォントが異なるシステムによって決まることに注意する必要があります.システムのフォントパスが見つからない場合は、設定しなくてもいいです.次に、画像に干渉線をいくつか描きます.最後にねじれを作成し、フィルタを加えて検証コードの効果を強化します.
以下は、検証コードピクチャを生成する完全なコードと実行効果です.
通常、Python環境のほかにPILライブラリが必要ですが、PILライブラリの役割は前のブログを参照してください.検証コードピクチャを生成する場合は、まず26文字の大文字と小文字、10文字のランダム文字列を生成します.次に画像を作成し、文字列を書き込むには、この中のフォントが異なるシステムによって決まることに注意する必要があります.システムのフォントパスが見つからない場合は、設定しなくてもいいです.次に、画像に干渉線をいくつか描きます.最後にねじれを作成し、フィルタを加えて検証コードの効果を強化します.
以下は、検証コードピクチャを生成する完全なコードと実行効果です.
# coding = utf-8
import random, string, sys, math
from PIL import Image, ImageDraw, ImageFont, ImageFilter
font_path = 'C:\Windows\Fonts\simfang.ttf' #
number = 4 #
size = (80, 30) #
bgcolor = (255, 255, 255) #
fontcolor = (0, 0, 255) #
linecolor = (255, 0, 0) # ,
draw_line = True #
line_number = (1, 5) #
#
def gene_text():
# source = list(string.letters)
"""
source = ['a', 'b', 'c', 'd', 'e',
'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o',
'p', 'q', 'r', 's', 't',
'u', 'v', 'w', 'x', 'y', 'z']
"""
source = list(string.ascii_letters)
for index in range(0, 10):
source.append(str(index))
return ''.join(random.sample(source, number)) # number
#
def gene_line(draw, width, height):
begin = (random.randint(0, width), random.randint(0, height))
end = (random.randint(0, width), random.randint(0, height))
draw.line([begin, end], fill=linecolor)
#
def gene_code():
width, height = size #
image = Image.new('RGBA', (width, height), bgcolor) #
font = ImageFont.truetype(font_path, 25) #
draw = ImageDraw.Draw(image) #
text = gene_text() #
font_width, font_height = font.getsize(text)
draw.text(((width - font_width) / number, (height - font_height) / number), text
, font=font, fill=fontcolor) #
if draw_line:
gene_line(draw, width, height)
image = image.transform((width+20, height+10), Image.AFFINE,
(1, -0.3, 0, -0.1, 1, 0), Image.BILINEAR) #
image = image.filter(ImageFilter.EDGE_ENHANCE_MORE) #
image.save('indecode.png')
if __name__ == "__main__":
gene_code()