Skip to content

Commit 79921e5

Browse files
committed
improved captcha resolution
Signed-off-by: zhangtianli2006 <zhangtianli2006@163.com>
1 parent 3f99d39 commit 79921e5

File tree

1 file changed

+34
-2
lines changed

1 file changed

+34
-2
lines changed

captcha/tools.py

Lines changed: 34 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
from django.utils import timezone
44
import datetime
55
import random
6+
import math
67
from PIL import Image, ImageDraw, ImageFont
78

89
from .apps import CaptchaConfig
@@ -33,8 +34,15 @@ def getRandomColor(self):
3334
def getRandomChar(self):
3435
random_num = str(random.randint(0, 9)) # numbers
3536
random_lower = chr(random.randint(97, 122)) # lower case letters
36-
random_upper = chr(random.randint(65, 90)) # upper case letters
37+
random_upper = chr(random.randint(65, 90)) # upper case letters
38+
39+
while random_lower == 'o':
40+
random_lower = chr(random.randint(97, 122))
41+
while random_upper == 'O':
42+
random_upper = chr(random.randint(65, 90))
43+
3744
random_char = random.choice([random_num, random_lower, random_upper])
45+
3846
return random_char
3947

4048
# draw random lines to interfere
@@ -57,6 +65,30 @@ def drawPoint(self, draw):
5765
y = random.randint(0, self.height)
5866
draw.point((x,y), fill = self.getRandomColor())
5967

68+
def checkSimilarity(self, color1, color2):
69+
r1 = color1[0]
70+
g1 = color1[1]
71+
b1 = color1[2]
72+
73+
r2 = color2[0]
74+
g2 = color2[1]
75+
b2 = color2[2]
76+
77+
r3 = (r1 - r2) / 256
78+
g3 = (g1 - g2) / 256
79+
b3 = (b1 - b2) / 256
80+
81+
color_diff = math.sqrt(r3 ** 2 + g3 ** 2 + b3 ** 2)
82+
83+
bright1 = ((r1 * 299) + (g1 * 587) + (b1 * 114))
84+
bright2 = ((r2 * 299) + (g2 * 587) + (b2 * 114))
85+
86+
bright_diff = abs(bright1 - bright2)
87+
88+
if color_diff < 0.7 or bright_diff < 100 * 255:
89+
return True
90+
return False
91+
6092
# create random picture
6193
# @param -> img save path
6294
# @return -> answer
@@ -79,7 +111,7 @@ def createImg(self, path):
79111
random_txt = self.getRandomChar()
80112
txt_color = self.getRandomColor()
81113
# avoid the text color is same to background color
82-
while txt_color == bg_color:
114+
while self.checkSimilarity(bg_color, txt_color):
83115
txt_color = self.getRandomColor()
84116

85117
# draw text

0 commit comments

Comments
 (0)