python使用pil產生圖片驗證碼的方法

來源:互聯網
上載者:User

python使用pil產生圖片驗證碼的方法

   這篇文章主要介紹了python使用pil產生圖片驗證碼的方法,涉及Python操作Image,ImageDraw,ImageFont等模組的相關技巧,需要的朋友可以參考下

  ?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

# -*- coding: utf-8 -*-

#匯入三個模組

import Image,ImageDraw,ImageFont

import random

import math

'''準系統'''

#圖片寬度

width = 100

#圖片高度

height = 40

#背景顏色

bgcolor = (255,255,255)

#產生背景圖片

image = Image.new('RGB',(width,height),bgcolor)

#載入字型

font = ImageFont.truetype('FreeSans.ttf',30)

#字型顏色

fontcolor = (0,0,0)

#產生draw對象,draw是一些演算法的集合

draw = ImageDraw.Draw(image)

#畫字型,(0,0)是起始位置

draw.text((0,0),'1234',font=font,fill=fontcolor)

#釋放draw

del draw

#儲存原始版本

image.save('1234_1.jpeg')

'''示範扭曲,需要建立一個圖片對象'''

#新圖片

newImage = Image.new('RGB',(width,height),bgcolor)

#load像素

newPix = newImage.load()

pix = image.load()

offset = 0

for y in range(0,height):

offset += 1

for x in range(0,width):

#新的x座標點

newx = x + offset

#你可以試試如下的效果

#newx = x + math.sin(float(y)/10)*10

if newx < width:

#把源像素通過位移到新的像素點

newPix[newx,y] = pix[x,y]

#儲存扭曲後的版本

newImage.save('1234_2.jpeg')

'''形變一下'''

#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')

'''畫幹擾線,別畫太多,免得使用者都看不清楚'''

#建立draw,畫線用

draw = ImageDraw.Draw(newImage)

#線的顏色

linecolor= (0,0,0)

for i in range(0,15):

#都是隨機的

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)

#儲存到本地

newImage.save('1234_4.jpeg')

  希望本文所述對大家的Python程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.