PIL是Python的标准内置库(仅支持python2.7),所以在PIL库基础上进行了兼容升级(支持python3.x,增长新功能方法)版本,名字叫Pillow。html
一、下载安装python
pip3 install pillow
二、Image类python3.x
Image类是pillow库中最重要的类,所以将Image类中的经常使用功能和主要方法列举出来,其余类的功能函数和主要方法详细,可去官网查询:官方文档 参考文档2,参考文档3。dom
""" ####Image经常使用建立对象实例的类 Image.new(mode,size,color) #'RGB',(1920,1080),(255,0,0) 使用给定的模式、大小和颜色建立新图像 Image.open(file,mode):#Image.open('path/to/imagefile.jpg') 读取图像文件 ####Image对象实例方法 im.convert(mode):#image1.convert('L')将图像转换为另外一种模式,而后返回新图像 im.copy():拷贝图像 im.crop(box):从当前图像返回矩形区域的副本,box是一个4元祖,定义从左、上、右、下的像素坐标 im.filter(filter):返回由给定过滤器过滤的图像的副本 im.getbands():返回包含每一个band的名称的元组。例如, RGB图像上的getband返回(“R”,“G”,“B”) im.getbbox():计算图像中非零区域的边界框 im.getcolors(maxcolors):返回元祖的末排序列表 im.getdata():将图像的内容做为包含像素值的序列对象返回 im.getextrema():返回包含图像最小值和最大值的2元组,仅适用于单波段图像 im.getpixel(xy):返回给定位置的像素。若是图像是多层图像,则此方法返回元组 im.load():映像分配存储并从文件加载它 im.point(table):返回图像的副本,其中每一个像素已经过给定的查找表进行映射 im.resize(size,filter=None):返回图像的已调整大小的副本 im.rotate(angle):返回围绕其中心逆时针旋转给定度数的图像副本 im.save(outfile,format,options):将图像保存在给定的文件名下 im.seek(frame):寻找序列文件中的给定帧 im.show():显示图像 im.split():返回图像中各个图像带的元组 im.tell():返回当前帧编号 im.thumbnail(size):修改图像以包含其自身的缩略图版本 im.paste(image,box):将另外一张图像粘贴到此图像中 im.transpose(method):返回图像的翻转或旋转副本 im.verify():尝试肯定文件是否损坏,而不实际解码图像数据 im.format:源文件的文件格式 im.mode:图像模式典型值为“1”,“L”,“RGB”或“CMYK” im.size:图像大小,以像素为单位。大小以2元组(宽度,高度)给出 im.palette:调色板表 im.info:保存与图像相关的数据的字典 """
三、示例:python2.7
1 from PIL import Image 2 3 char_list = list("test") 4 img = Image.open("1539319477.jpg").convert("L") 5 img = img.resize((int(img.size[1]*0.6), int(img.size[0]*0.6))) # 对图像进行必定缩小 6 7 8 def convert(img): 9 img = img.convert("L") # 转为灰度图像 10 txt = "" 11 for i in range(img.size[1]): 12 for j in range(img.size[0]): 13 gray = img.getpixel((j, i)) # 获取每一个坐标像素点的灰度 14 txt += char_list[int(gray / 64)] # 获取对应坐标的字符值 15 txt += '\n' 16 return txt 17 18 txt = convert(img) 19 with open("convert.txt", "w") as f: 20 f.write(txt) # 存储到文件中
1 from PIL import Image, ImageDraw, ImageFont, ImageFilter 2 3 import random 4 5 6 # 随机字母: 7 def random_char(): 8 return chr(random.randint(65, 90)) 9 10 11 # 随机颜色1: 12 def random_color(): 13 return (random.randint(0, 255), 14 random.randint(0, 255), 15 random.randint(0, 255)) 16 17 18 # 随机颜色2: 19 def random_color_1(): 20 return (random.randint(0, 255), 21 random.randint(0, 255), 22 random.randint(0, 255)) 23 24 25 def create_check_code(): 26 width = 240 27 height = 60 28 image = Image.new('RGB', (width, height), (225, 225, 225)) 29 # 建立Font对象: 30 font = ImageFont.truetype('Monaco.ttf', 36) 31 # 建立Draw对象: 32 draw = ImageDraw.Draw(image) 33 # 填充每一个像素: 34 for x in range(width): 35 for y in range(height): 36 draw.point((x, y), fill=random_color()) 37 # 输出文字: 38 for t in range(4): 39 draw.text((60 * t + 10, 10), random_char(), font=font, fill=random_color_1()) 40 # 模糊: 41 image = image.filter(ImageFilter.BLUR) 42 image.save('code.jpg', 'jpeg') 43 image.show() 44 45 create_check_code()
1 import random 2 from PIL import Image, ImageDraw, ImageFont, ImageFilter 3 4 _letter_cases = "abcdefghjkmnpqrstuvwxy" # 小写字母,去除可能干扰的i,l,o,z 5 _upper_cases = _letter_cases.upper() # 大写字母 6 _numbers = ''.join(map(str, range(3, 10))) # 数字 7 init_chars = ''.join((_letter_cases, _upper_cases, _numbers)) 8 9 10 def create_validate_code(size=(120, 30), 11 chars=init_chars, 12 img_type="GIF", 13 mode="RGB", 14 bg_color=(255, 255, 255), 15 fg_color=(0, 0, 255), 16 font_size=18, 17 font_type="Monaco.ttf", 18 length=4, 19 draw_lines=True, 20 n_line=(1, 2), 21 draw_points=True, 22 point_chance=2): 23 """ 24 @todo: 生成验证码图片 25 @param size: 图片的大小,格式(宽,高),默认为(120, 30) 26 @param chars: 容许的字符集合,格式字符串 27 @param img_type: 图片保存的格式,默认为GIF,可选的为GIF,JPEG,TIFF,PNG 28 @param mode: 图片模式,默认为RGB 29 @param bg_color: 背景颜色,默认为白色 30 @param fg_color: 前景色,验证码字符颜色,默认为蓝色#0000FF 31 @param font_size: 验证码字体大小 32 @param font_type: 验证码字体,默认为 ae_AlArabiya.ttf 33 @param length: 验证码字符个数 34 @param draw_lines: 是否划干扰线 35 @param n_lines: 干扰线的条数范围,格式元组,默认为(1, 2),只有draw_lines为True时有效 36 @param draw_points: 是否画干扰点 37 @param point_chance: 干扰点出现的几率,大小范围[0, 100] 38 @return: [0]: PIL Image实例 39 @return: [1]: 验证码图片中的字符串 40 """ 41 42 width, height = size # 宽高 43 # 建立图形 44 img = Image.new(mode, size, bg_color) 45 draw = ImageDraw.Draw(img) # 建立画笔 46 47 def get_chars(): 48 """生成给定长度的字符串,返回列表格式""" 49 return random.sample(chars, length) 50 51 def create_lines(): 52 """绘制干扰线""" 53 line_num = random.randint(*n_line) # 干扰线条数 54 55 for i in range(line_num): 56 # 起始点 57 begin = (random.randint(0, size[0]), random.randint(0, size[1])) 58 # 结束点 59 end = (random.randint(0, size[0]), random.randint(0, size[1])) 60 draw.line([begin, end], fill=(0, 0, 0)) 61 62 def create_points(): 63 """绘制干扰点""" 64 chance = min(100, max(0, int(point_chance))) # 大小限制在[0, 100] 65 66 for w in range(width): 67 for h in range(height): 68 tmp = random.randint(0, 100) 69 if tmp > 100 - chance: 70 draw.point((w, h), fill=(0, 0, 0)) 71 72 def create_strs(): 73 """绘制验证码字符""" 74 c_chars = get_chars() 75 strs = ' %s ' % ' '.join(c_chars) # 每一个字符先后以空格隔开 76 77 font = ImageFont.truetype(font_type, font_size) 78 font_width, font_height = font.getsize(strs) 79 80 draw.text(((width - font_width) / 3, (height - font_height) / 3), 81 strs, font=font, fill=fg_color) 82 83 return ''.join(c_chars) 84 85 if draw_lines: 86 create_lines() 87 if draw_points: 88 create_points() 89 strs = create_strs() 90 91 # 图形扭曲参数 92 params = [1 - float(random.randint(1, 2)) / 100, 93 0, 94 0, 95 0, 96 1 - float(random.randint(1, 10)) / 100, 97 float(random.randint(1, 2)) / 500, 98 0.001, 99 float(random.randint(1, 2)) / 500 100 ] 101 img = img.transform(size, Image.PERSPECTIVE, params) # 建立扭曲 102 103 img = img.filter(ImageFilter.EDGE_ENHANCE_MORE) # 滤镜,边界增强(阈值更大) 104 105 return img, strs