python使用PIL實現(xiàn)多張圖片垂直合并
更新時間:2019年01月15日 10:37:29 作者:修煉打怪的小烏龜
這篇文章主要為大家詳細介紹了python使用PIL實現(xiàn)多張圖片垂直合并,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了python實現(xiàn)多張圖片垂直合并的具體代碼,供大家參考,具體內(nèi)容如下
# coding: utf-8
# image_merge.py
# 圖片垂直合并
# http://www.redicecn.com
# redice@163.com
import os
import Image
def image_resize(img, size=(1500, 1100)):
"""調(diào)整圖片大小
"""
try:
if img.mode not in ('L', 'RGB'):
img = img.convert('RGB')
img = img.resize(size)
except Exception, e:
pass
return img
def image_merge(images, output_dir='output', output_name='merge.jpg', \
restriction_max_width=None, restriction_max_height=None):
"""垂直合并多張圖片
images - 要合并的圖片路徑列表
ouput_dir - 輸出路徑
output_name - 輸出文件名
restriction_max_width - 限制合并后的圖片最大寬度,如果超過將等比縮小
restriction_max_height - 限制合并后的圖片最大高度,如果超過將等比縮小
"""
max_width = 0
total_height = 0
# 計算合成后圖片的寬度(以最寬的為準)和高度
for img_path in images:
if os.path.exists(img_path):
img = Image.open(img_path)
width, height = img.size
if width > max_width:
max_width = width
total_height += height
# 產(chǎn)生一張空白圖
new_img = Image.new('RGB', (max_width, total_height), 255)
# 合并
x = y = 0
for img_path in images:
if os.path.exists(img_path):
img = Image.open(img_path)
width, height = img.size
new_img.paste(img, (x, y))
y += height
if restriction_max_width and max_width >= restriction_max_width:
# 如果寬帶超過限制
# 等比例縮小
ratio = restriction_max_height / float(max_width)
max_width = restriction_max_width
total_height = int(total_height * ratio)
new_img = image_resize(new_img, size=(max_width, total_height))
if restriction_max_height and total_height >= restriction_max_height:
# 如果高度超過限制
# 等比例縮小
ratio = restriction_max_height / float(total_height)
max_width = int(max_width * ratio)
total_height = restriction_max_height
new_img = image_resize(new_img, size=(max_width, total_height))
if not os.path.exists(output_dir):
os.makedirs(output_dir)
save_path = '%s/%s' % (output_dir, output_name)
new_img.save(save_path)
return save_path
if __name__ == '__main__':
image_merge(images=['900-000-000-0501a_b.jpg', '900-000-000-0501b_b.JPG', '1216005237382a_b.jpg'])
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Python判斷字符串是否為字母或者數(shù)字(浮點數(shù))的多種方法
本文給大家?guī)砣N方法基于Python判斷字符串是否為字母或者數(shù)字(浮點數(shù)),非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2018-08-08
我在七夕佳節(jié)用Python制作的表白神器,程序員也應(yīng)該擁有愛情!建議收藏
這篇文章主要介紹了我在七夕佳節(jié)用Python制作的表白神器,建議收藏,程序員也該擁有愛情,感興趣的小伙伴快來看看吧2021-08-08
python中文件變化監(jiān)控示例(watchdog)
這篇文章主要介紹了python中文件變化監(jiān)控示例(watchdog),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-10-10
python使用requests+excel進行接口自動化測試的實現(xiàn)
在當今的互聯(lián)網(wǎng)時代中,接口自動化測試越來越成為軟件測試的重要組成部分,本文就來介紹了python使用requests+excel進行接口自動化測試的實現(xiàn),感興趣的可以了解一下2023-11-11
Python常見的2種運行方式:Python Shell和IDLE
Python支持多種運行方式,本文主要介紹了Python常見的2種運行方式:Python Shell和IDLE,文中通過圖文示例介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2025-02-02
torch 中各種圖像格式轉(zhuǎn)換的實現(xiàn)方法
這篇文章主要介紹了torch 中各種圖像格式轉(zhuǎn)換的實現(xiàn)方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-12-12

