python圖像處理庫:Pillow初級教程
Image類
Image.resize()和Image.thumbnail()的區別
根據代碼和代碼注釋, 這兩個函數都是對圖片進行縮放, 兩者的主要區別如下:
- resize()函數會返回一個Image對象, thumbnail()函數返回None
- resize()修改后的圖片在返回的Image中, 而原圖片沒有被修改;
- thumbnail()直接對內存中的原圖進行了修改, 但是修改需要保存
- resize()中的size參數直接設定了resize之后圖片的規格,而thumbnail()中的size參數則是設定了x/y上的最大值. 也就是說, 經過resize()處理的圖片可能會被拉伸,而經過thumbnail()處理的圖片不會被拉伸
thumbnail()函數內部調用了resize(), 可以認為thumbnail()是對resize()的一種封裝
Pillow中最重要的類就是Image,該類存在於同名的模塊中。可以通過以下幾種方式實例化:從文件中讀取圖片,處理其他圖片得到,或者直接創建一個圖片。
使用Image模塊中的open函數打開一張圖片:
>>> from PIL import Image >>> im = Image.open("lena.ppm")
如果打開成功,返回一個Image對象,可以通過對象屬性檢查文件內容
>>> from __future__ import print_function >>> print(im.format, im.size, im.mode) PPM (512, 512) RGB
format屬性定義了圖像的格式,如果圖像不是從文件打開的,那么該屬性值為None;size屬性是一個tuple,表示圖像的寬和高(單位為像素);mode屬性為表示圖像的模式,常用的模式為:L為灰度圖,RGB為真彩色,CMYK為pre-press圖像。
如果文件不能打開,則拋出IOError異常。
當有一個Image對象時,可以用Image類的各個方法進行處理和操作圖像,例如顯示圖片:
>>> im.show()
創建縮略圖 --> 常用方式, 但有限制, 看源碼解釋
如果有寬或長大於了, 測試出來的結果感覺有點像成比例似的
x, y = self.size
if x > size[0]:
y = int(max(y * size[0] / x, 1))
x = int(size[0])
if y > size[1]:
x = int(max(x * size[1] / y, 1))
y = int(size[1])
size = x, y
#!/usr/bin/env python # -*- coding:utf-8 -*- # -----<縮略圖>----- # import os, datetime from PIL import Image def ThumbNailImg(infile): # 略縮圖路徑 outfile = os.path.splitext(infile)[0] + "_ThumbNail" + ".jpeg" im = Image.open(infile) size = (206, 206) im.thumbnail(size, Image.ANTIALIAS) im.save(outfile) return outfile
精確指定圖片寬、高
def make_thumb(path, size): """生成縮略圖""" img = Image.open(path) width, height = img.size # 裁剪圖片成正方形 if width > height: delta = (width - height) / 2 box = (delta, 0, width - delta, height) region = img.crop(box) elif height > width: delta = (height - width) / 2 box = (0, delta, width, height - delta) region = img.crop(box) else: region = img # 縮放 thumb = region.resize((900, 500), Image.ANTIALIAS) filename = os.path.splitext(path)[0] + "_ThumbNail" + ".gif" print(filename) # 保存 thumb.save(filename, quality=70)
上下拼接圖片
參考鏈接: https://blog.csdn.net/jiaju_cao/article/details/16958185
def merge_thumb(files, output_file): """上下合並圖片""" imgs = [] width = 0 height = 0 # 計算總寬度和長度 print(files) for file in files: img = Image.open(file) if img.mode != 'RGB': img = img.convert('RGB') imgs.append(img) if img.size[0] > width: width = img.size[0] height += img.size[1] # 新建一個白色底的圖片 merge_img = Image.new('RGB', (width, height), 0xffffff) cur_height = 0 for img in imgs: # 把圖片粘貼上去 merge_img.paste(img, (0, cur_height)) cur_height += img.size[1] print(output_file) merge_img.save(output_file, quality=70) if __name__ == '__main__': # 上下合並圖片 THUMB_PATH = "/opt/code/my_code/tornado_uedit" # ['/opt/code/my_code/tornado_uedit/143351404554_ThumbNail.gif', '/opt/code/my_code/tornado_uedit/171047953516_ThumbNail.gif'] files = glob.glob(os.path.join(THUMB_PATH, '*_ThumbNail.gif')) merge_output = os.path.join(THUMB_PATH, 'thumbs.gif') merge_thumb(files, merge_output)
glob模塊,glob.glob(pathname),返回所有匹配的文件路徑列表