- 生成一張帶有噪點的驗證碼圖片
from PIL import Image, ImageDraw, ImageFont
import random
def getRandomColor():
'''獲取一個隨機顏色(r, g, b)格式的'''
c1 = random.randint(0, 255)
c2 = random.randint(0, 255)
c3 = random.randint(0, 255)
return (c1, c2, c3)
def getRandomStr():
'''獲取一個隨機字符串,每個字符的顏色也是隨機的'''
random_num = str(random.randint(0, 9))
random_low_alpha = chr(random.randint(97, 122))
random_upper_alpha = chr(random.randint(65, 90))
random_char = random.choice([random_num, random_low_alpha, random_upper_alpha])
return random_char
# 獲取一個Image對象,參數分別是RGB模式。寬150,高30, 隨機顏色
image = Image.new('RGB', (150, 30), getRandomColor())
# 獲取一個畫筆對象,將圖片對象傳過去
draw = ImageDraw.Draw(image)
# 獲取一個font字體對象參數是ttf的字體的目錄。以及字體的大小
font = ImageFont.truetype('arial.ttf', size=26)
for i in range(5):
# 循環5次,獲取5個隨機字符串
random_char = getRandomStr()
# 在圖片上一次寫入得到的隨機字符串,參數是:定位,字符串,顏色,字體
draw.text((10 + i * 30, -2), random_char, getRandomColor(), font=font)
# 噪點噪線
# 劃線
width = 150
height = 30
for i in range(5):
x1 = random.randint(0, width)
x2 = random.randint(0, width)
y1 = random.randint(0, height)
y2 = random.randint(0, height)
draw.line((x1, x2, y1, y2), fill=getRandomColor())
# 畫點
for i in range(self.point_count):
draaw.point([random.randint(0, width), random.randint(0, height)], fill=getRandomColor())
x = random.randint(0, width)
y = random.randint(0, height)
draw.arc((x, y, x + 4, y + 4), 0, 90, fill=getRandomColor())
# 保存到硬盤,名爲test.png格式的png圖片
image.save(open('test.png', 'wb'), 'png')
代碼效果如圖:
2.對驗證碼圖片生成進行封裝
from PIL import Image, ImageDraw, ImageFont
import random
class CodeImg:
def __init__(self, width=150, height=30, code_count=5, font_size=32, point_count=20, line_count=3, img_format='png'):
self.width = width
self.height = height
self.code_count = code_count
self.font_size = font_size
self.point_count = point_count
self.line_count = line_count
self.img_format = img_format
'''
可以生成一個經過降噪後的隨機驗證碼的圖片
code_count:驗證碼個數 point_count:噪點個數
line_count:劃線個數 img_format:圖片格式
return 生成的圖片的bytes類型的data
'''
@staticmethod
def getRandomColor():
'''獲取一個隨機顏色(r, g, b)格式的'''
c1 = random.randint(0, 255)
c2 = random.randint(0, 255)
c3 = random.randint(0, 255)
return (c1, c2, c3)
@staticmethod
def getRandomStr():
'''獲取一個隨機字符串,每個字符的顏色也是隨機的'''
random_num = str(random.randint(0, 9))
random_low_alpha = chr(random.randint(97, 122))
random_upper_alpha = chr(random.randint(65, 90))
random_char = random.choice([random_num, random_low_alpha, random_upper_alpha])
return random_char
def getCodeImg(self):
# 獲取一個Image對象,參數分別是RGB模式。寬150,高30, 隨機顏色
image = Image.new('RGB', (self.width, self.height), self.getRandomColor())
# 獲取一個畫筆對象,將圖片對象傳過去
draw = ImageDraw.Draw(image)
# 獲取一個font字體對象參數是ttf的字體的目錄。以及字體的大小
font = ImageFont.truetype('arial.ttf', size=self.font_size)
temp = []
for i in range(self.code_count):
# 循環5次,獲取5個隨機字符串
random_char = self.getRandomStr()
# 在圖片上一次寫入得到的隨機字符串,參數是:定位,字符串,顏色,字體
draw.text((10 + i * 30, -2), random_char, self.getRandomColor(), font=font)
# 保存隨機字符,以供驗證用戶輸入的驗證碼是否正確使用
temp.append(random_char)
valid_str = ''.join(temp)
# 噪點噪線
# 劃線
for i in range(self.line_count):
x1 = random.randint(0, self.width)
x2 = random.randint(0, self.width)
y1 = random.randint(0, self.height)
y2 = random.randint(0, self.height)
draw.line((x1, x2, y1, y2), fill=self.getRandomColor())
# 畫點
for i in range(self.point_count):
draaw.point([random.randint(0, self.width), random.randint(0, self.height)], fill=self.getRandomColor())
x = random.randint(0, self.width)
y = random.randint(0, self.height)
draw.arc((x, y, x + 4, y + 4), 0, 90, fill=self.getRandomColor())
# 在內存生成圖片
from io import BytesIO
f = BytesIO()
image.save(f, self.img_format)
data = f.getvalue()
f.close()
return data, vaild_str
if __name__ == '__main__':
img = CodeImg()
data, vaild_str = img.getCodeImg()
print(valid_str)
f = open('text.png', 'wb')
f.write(data)
代碼效果如圖:
- 干擾圓圈,隨機生成兩條直線
from PIL import Image, ImageDraw, ImageFont, ImageFilter
import random
# 隨機數字
def rnd_char():
return chr(random.randint(65, 90))
# 隨機顏色
def rnd_color():
return random.randint(0, 245), random.randint(0, 245), random.randint(0, 245)
# 生成驗證碼和圖片
def generate_code(file_name="code"):
width = 60 * 4
height = 60
image = Image.new('RGB', (width, height), (255, 255, 255))
# 創建Font對象
font = ImageFont.truetype('arial.ttf', 36)
# 創建Draw對象
draw = ImageDraw.Draw(image)
# 隨機生成兩條直線(一條貫穿上半部,一條貫穿下半部)
draw.line((0, 0 + random.randint(0, height // 2), width, 0 + random.randint(0, height // 2)), fill=rnd_color())
draw.line((0, height - random.randint(0, height // 2), width, height - random.randint(0, height // 2)), fill=rnd_color())
# 輸出文字
code_str = ''
for t in range(4):
tmp = rnd_char()
draw.text((60 * t + 10, 10), tmp, font=font, fill=rnd_color())
code_str += tmp
#干擾點
for i in range(40):
draw.point([random.randint(0, width), random.randint(0, height)], fill=rnd_color())
# 干擾圓圈
for i in range(40):
draw.point([random.randint(0, width), random.randint(0, height)], fill=rnd_color())
x = random.randint(0, width)
y = random.randint(0, height)
draw.arc((x, y, x + 4, y + 4), 0, 90, fill=rnd_color())
# 扭曲
image = image.transform((width + 20, height + 10), Image.AFFINE, (1, -0.3, 0, -0.1, 1, 0), Image.BILINEAR)
# 模糊處理
image = image.filter(ImageFilter.BLUR)
image.save(file_name + '.png', 'png')
return code_str, file_name
if __name__ == '__main__':
for i in range(1):
generate_code('code%d' % i)
代碼效果如圖:
4. 在圖片上添加字體
from PIL import Image, ImageDraw, ImageFont
# 指定要使用的字體和大小
font = ImageFont.truetype('simhei.ttf', 34)
# image:圖片 text:要添加的文本 font:字體
def add_text_to_image(image, text, font=font):
rgba_image = image.convert('RGBA')
tetx_overlay = Image.new('RGB', rgba_image.size, (255, 255, 255, 0))
image_draw = ImageDraw.Draw(text_overlay)
text_size_x, text_size_y = image_draw.tetxsize(text, font=font)
# 設置文本文字位置
print(rgba_image)
text_xy = (rgba_image.size[0] - text_size_x, rgba_image.size[1] - text_size_y)
# 設置文本顏色和透明度
image_draw.tetx(tetx_xy, text, font=font, fill=(76, 234, 124, 180))
image_with_text = Image.alpha_composite(rgba_image, text_overlay)
return image_with_text
im_before = Image.open("萌.png")
im_before.show()
im_after = add_text_to_image(im_before, '花花萌萌噠')
im_after.show()
im_after.save('im_after.png')
代碼效果如圖:
5. 方法二:圖片添加字體
from PIL import Image, ImageDraw, ImageFont
# add_text
im = Image.open('萌.jpg')
im_to_draw = im.copy()
draw = ImageDraw.Draw(im_to_draw)
font = ImageFont.truetype('simhei.ttf', 40)
text = '華晨宇萌萌噠'
position_x, position_y = (20, 20)
color = (255, 0, 0)
draw.text((position_x, position_y), text, color, font=font)
im_to_draw.save('im_draw_font.jpg')
im_to_draw.show()
代碼效果如圖:
6.字符畫 哆啦A夢
from PIL import Image
ascii_char = list('1 ')
def get_char(r, g, b, alpha=256):
if alpha == 0:
return ' '
gray = int(0.2126 * r + 0.7152 * g + 0.0722 * b)
unit = 256 / len(ascii_char)
return ascii_char[int(gray // unit)]
def maiin():
im = Image.open('多.png')
WIDTH, HEIGHT = 80, 48
im = im.resize((WIDTH, HEIGHT))
# im.resize(size, resample=0) --調整大小
text = ''
for i in range(HEIGHT):
for j in range(WIDTH):
text += get_char(* im.getpixel((j, i)))
txt += '\n'
fo = open("哆啦A夢.txt", "w")
fo.write(txt)
fo.close()
main()
原圖效果:
代碼效果如圖: