環境:
win10、python2.7、PIL
需求:
使用python語言+PIL圖片處理庫實現美圖秀秀App版本圖片拼接功能;將多張圖片按照統一寬度1000px進行縮放,拉伸後,按照從上到下的順序拼接爲一張長圖。
效果:
原始的2張圖片
拼接之後的圖片
思路:
1,PIL庫實現圖片的大小處理
def resize():
im = Image.open(path) #path 爲圖片地址
width, height = im.size #獲取圖片分辨率
heightNew = int(height/(width/1000.0)) #計算resize之後的新高度
imResized = im.resize((1000,heightNew),Image.ANTIALIAS) #im.resize(新尺寸,拉伸模式); 新的分辨率只能是整數
#拉伸模式參數爲可選,默認空值處理後的圖片質量較低;Image.ANTIALIAS 質量高
2,將處理後的圖片拷貝到最終生成的目標圖片
def paste():
finalImage = Image.new('RGBA',(width,height)) #width, height 爲新圖片的分辨率
im = Image.open(path) #原始圖片Image對象
#將原始圖片拷貝到新圖片中;(x,y)表示原始圖片的左上角在新圖片中的位置;圖片左上角的座標值爲(0,0)
finalImage.paste(im,(x,y))
finalImage.save(save_path) #save_path 新圖片的地址;例如:D:\\pic\\pic_new.png
完整代碼:
#coding:utf-8
import PIL.Image as Image
import os
import datetime
#獲取指定目錄下的所有文件的絕對路徑
def getPicPathList(directory):
fileNames = os.listdir(directory)
picPathList = []
for fileName in fileNames:
picPathList.append(os.path.join(directory,fileName))
return picPathList
#傳入文件的絕對路徑,默認圖片格式都爲png格式, 生成拼接後的圖片
def mergePic(picPathList, mergedPicPath):
sumHeight = 0 #獲取縮放之後的新圖片整體高度
for path in picPathList:
im = Image.open(path)
width, height = im.size
height = height/(width/1000.0)
sumHeight = sumHeight + int(height)
finalImage = Image.new('RGBA',(1000,sumHeight))
currentY = 0 #下一張要粘貼到新圖片的原始圖,在新圖片中的Y座標
for path in picPathList:
im = Image.open(path)
width, height = im.size
#圖片拉伸
heightNew = int(height/(width/1000.0))
imResized = im.resize((1000,heightNew),Image.ANTIALIAS)
#粘貼到最終生成的圖上
finalImage.paste(imResized,(0,currentY))
currentY = currentY +heightNew
#保存圖片
finalImage.save(mergedPicPath)
#---------------main start-----------------------
pic_dir = "D:\\test" #要合併的圖片存放的文件夾路徑
# pic_dir = unicode(pic_dir,'utf-8') #pyhton2.7,如果路徑中包含中文需要進行unicode轉碼
picPathList = getPicPathList(pic_dir)
#新圖片保存到要合併截圖的文件夾目錄,當前時間命名
now_time = datetime.datetime.now();
fileName = now_time.strftime('%Y%m%d%H%M%S') + '.png' #根據當前時間生成新圖片名稱;
mergedPicPath = os.path.join(pic_dir, fileName) #合併完成之後新圖片的路徑
mergePic(picPathList,mergedPicPath)
#---------------main end-----------------------
注意:
1,默認要合併的文件夾中的圖片都爲.png格式,最終生成的圖片也固定爲.png圖片;暫時沒有對合並文件夾中多種圖片格式做處理,以及圖片文件的篩選;建議原始圖片和最終生成的圖片格式一致;
2,pyhton2.7,如果路徑中包含中文需要進行unicode轉碼
參考鏈接:
Python圖像庫PIL的類Image及其方法介紹
Python的PIL庫中的paste方法
python listdir() 中文路徑 中文文件夾 亂碼 解決方法
操作文件和目錄:listdir--遍歷所有文件
python中加入中文註釋報錯處理
Python 幾種取整的方法
python 判斷是否爲一個文件或文件夾
python獲取當前時間的用法