08 图像处理——生成二维码和验证码

生成二维码和验证码

  • 9.2 关键技术
    • 1、qrcode库的使用
    • 2、PIL库(图像归档 和 图像处理)的使用
  • 9.3 二维码生成和解析程序设计的步骤
    • 1、生成带有图标的二维码
    • 2、Python解析二维码图片(只有Python2.7以下才有zbarlight)
  • 9.4 用Python生成验证码图片

9.2 关键技术

1、qrcode库的使用

import qrcode
img = qrcode.make('http://www.zut.edu.cn')
img.save('xinxing.png')

# 用QRCode类生成不用尺寸的二维码
import qrcode
qr = qrcode.QRCode(
    version = 1,
    error_correction = qrcode.constants.ERROR_CORRECT_L,
    box_size = 10,
    border = 4,
)
qr.add_data('https://www.taobao.com/')
qr.make(fit=True)
img = qr.make_image()
img.save('xinxingzhao.png')


# 将二维码图片转化为 SVG(矢量图)
import qrcode
import qrcode.image.svg
method = 'asd'
if method == 'basic':
    factory = qrcode.image.svg.SvgImage
elif method == 'fragment':
    factory = qrcode.image.svg.SvgFragmentImage
else:
    factory = qrcode.image.svg.SvgFillImage
img = qrcode.make('xinxingzhao', image_factory = factory)
img.save('xinxing.jpg')


2、PIL库(图像归档 和 图像处理)的使用

# Image模块
from PIL import Image
pil_im = Image.open('360截图20200207012217966.jpg')

newIm = Image.new('RGB', (640, 480), (255, 0, 0))

pil_im1 = Image.open('360截图20200207012252611.jpg').convert('L')



# ImageChops模块
from PIL import Image
im = Image.open('360截图20200207012217966.jpg')

from PIL import ImageChops
im_dup = ImageChops.duplicate(im) #  复制图片!!
print(im_dup.mode) # 输出RGB
im_diff = ImageChops.difference(im, im_dup)
im_diff.show() # 为黑图


# ImageDraw模块
from PIL import Image, ImageDraw

im = Image.open('13228499737707903.jpeg')
draw = ImageDraw.Draw(im)

draw.line((0, 0) + im.size, fill = 128) #  画原点到im.size的对角线!!!!!
draw.line((0, im.size[1], im.size[0], 0), fill=128)
im.show()


# ImageEnhance模块
from PIL import Image, ImageEnhance

im = Image.open('13228499737707903.jpeg')

enhancer = ImageEnhance.Brightness(im)  
im0 = enhancer.enhance(0.5) # 比原来图像降低一半亮度!
im0.show()


from PIL import Image, ImageFile, ImageFilter, ImageFont
# 图像的保存和打开提供了相关的支持功能
# 各种 滤波器的预定义集合,与Image类的filter()方法一起使用
# 其中 同名类,存储着bitmap字体,需要和ImageDraw类的text()方法一起使用

im = Image.open('13228499737707903.jpeg')
imout = im.filter(ImageFilter.BLUR)
print(imout.size) # s=输出:(4160, 2336)
imout.show()



9.3 二维码生成和解析程序设计的步骤

1、生成带有图标的二维码

import qrcode
from PIL import Image
import os, sys



def gen_qrcode(string, path, logo=''):
    # 初步生成二维码图像
    qr = qrcode.QRCode(
        version = 2,
        error_correction = qrcode.constants.ERROR_CORRECT_H,
        box_size = 8,
        border = 1
    )
    qr.add_data(string)
    qr.make(fit=True)
    
    # 获得Image实例并把颜色模式转换为RGBA
    img = qr.make_image()
    img = img.convert('RGBA')
    if logo and os.path.exists(logo):
        try:
            icon = Image.open(logo)
            img_w, img_h = img.size
        except Exception as e:
            print(e)
            sys.exit(1)
        factor = 4
        # 计算logo的尺寸
        size_w = int(img_w / factor)
        size_h = int(img_h / factor)
        # 比较并重新设置logo文件的尺寸
        icon_w, icon_h = icon.size
        if icon_w > size_w:
            icon_w = size_w
        if icon_h > size_h:
            icon_h = size_h
        icon = icon.resize((icon_w, icon_h), Image.ANTIALIAS)
        # 计算logo的位置,并复制到二维码图像中
        w = int((img_w-icon_w) / 2)
        h = int((img_h-icon_h) / 2)
        icon = icon.convert('RGBA')
        img.paste(icon, (w, h), icon)
        # 保存二维码
        img.save(path)



info = "https://baike.baidu.com/item/%E7%A7%91%E6%AF%94%C2%B7%E5%B8%83%E8%8E%B1%E6%81%A9%E7%89%B9/318773?fromtitle=%E7%A7%91%E6%AF%94&fromid=133066&fr=aladdin"
pic_path = 'qrcode.png'
logo_path = 'qq图片20200216205040.png'
gen_qrcode(info, pic_path, logo_path)


2、Python解析二维码图片(只有Python2.7以下才有zbarlight)

from pyzbar.pyzbar import decode
from PIL import Image, ImageEnhance
import os



def decode_qrcode(path):
    img = Image.open(path)
    result = decode(img)
    return result

decode_qrcode('qrcode.png')

[Decoded(data=b’https://baike.baidu.com/item/%E7%A7%91%E6%AF%94%C2%B7%E5%B8%83%E8%8E%B1%E6%81%A9%E7%89%B9/318773?fromtitle=%E7%A7%91%E6%AF%94&fromid=133066&fr=aladdin’, type=‘QRCODE’, rect=Rect(left=7, top=7, width=489, height=489), polygon=[Point(x=7, y=7), Point(x=9, y=496), Point(x=494, y=493), Point(x=496, y=9)])]

9.4 用Python生成验证码图片

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.ascii_letters) # 26个字母
    for index in range(0, 10): # 加上九个数字
        source.append(str(index))
    return ''.join(random.sample(source, 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)
    
    line_num = random.randint(line_number[0], line_number[1]) # 随机加上红色边界线!!
    while line_num:
        line_num -= 1
        gene_line(draw, width, height)
        
    image = image.transform((width+20, height+10), Image.AFFINE, (1, -0.1, 0, -0.1, 1, 0), Image.BILINEAR) # 扭曲
    image = image.filter(ImageFilter.EDGE_ENHANCE_MORE) # 滤镜, 边界加强
    
    image.save('idencode.png')
    

# 运行!
gene_code()

你可能感兴趣的:(十九个小项目,python)