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