python之PIL图像处理

PIL

PIL(Python Imaging Library)是Python中最常用的图像处理库,目前版本为 1.1.7,Image 类是 PIL 库中一个非常重要的类,通过这个类来创建实例可以有直接载入图像文件,读取处理过的图像和通过抓取的方法得到的图像这三种方法。

安装

注意:python3解释器会降级,降成python2,因为不支持,不过可以安装pillow

pip install PIL
使用

导入 Image 模块。然后通过 Image 类中的 open 方法即可载入一个图像文件。如果载入文件失败,则会引起一个 IOError ;若无返回错误,则 open 函数返回一个 Image 对象。

图片的缩放
from PIL import Image

# 1.打开文件,返回一个文件对象
img = Image.open('hello.png')

# 2.获取已有图片的尺寸
width,height = img.size

# 3.缩放图片10%
img.thumbnail(width/10,height/10)

# 4.把缩放的图片保存
img.save('hello1.png','png')
图片的模糊
from PIL import Image, ImageFilter

# 1 打开文件, 返回一个文件对象;
im = Image.open('hello.jpg')


# 2. 对图片进行模糊效果
im2 = im.filter(ImageFilter.BLUR)

# 4.把缩放的图片保存;
im2.save('hello2.png', 'png')
生成验证码
import random
import string
from PIL import Image, ImageDraw, ImageFont, ImageFilter

# ****************1. 可以单独为一个文件config.py文件 ***********************************
# 字体的位置,不同版本的系统会有不同
# font_path = '/opt/WebStorm-172.3544.34/jre64/lib/fonts/DroidSans-Bold.ttf'
font_path = '/opt/WebStorm-172.3544.34/jre64/lib/fonts/DroidSansMonoSlashed.ttf'
# 生成几位数的验证码
number = 4
# 生成验证码图片的高度和宽度
size = (100, 30)
# 背景颜色,默认为白色
bgcolor = (255,250,240)
# 字体颜色,默认为蓝色
fontcolor = (190,190,190)
# 干扰线颜色。默认为红色
linecolor = (255, 0, 0)
# 是否要加入干扰线
draw_line = True
# 加入干扰线条数的上下限
line_number = (1, 5)

# **************************2. 详细信息 *********************************************************
# 用来随机生成一个字符串
def gene_text():
    source = string.ascii_letters
    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+30,height+10), Image.AFFINE, (1,-0.3,0,-0.1,1,0),Image.BILINEAR)  #创建扭曲
    # 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('idencode.png')  # 保存验证码图片
    return image, str


if __name__ == "__main__":
    gene_code()

猜你喜欢

转载自blog.csdn.net/qq_41891803/article/details/81273205