python使用PIL实现多张图片垂直合并
更新时间:2019年01月15日 10:37:29 作者:修炼打怪的小乌龟
这篇文章主要为大家详细介绍了python使用PIL实现多张图片垂直合并,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
本文实例为大家分享了python实现多张图片垂直合并的具体代码,供大家参考,具体内容如下
# coding: utf-8
# image_merge.py
# 图片垂直合并
# http://www.redicecn.com
# redice@163.com
import os
import Image
def image_resize(img, size=(1500, 1100)):
"""调整图片大小
"""
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
# 产生一张空白图
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'])
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
相关文章
Python判断字符串是否为字母或者数字(浮点数)的多种方法
本文给大家带来三种方法基于Python判断字符串是否为字母或者数字(浮点数),非常不错,具有一定的参考借鉴价值,需要的朋友可以参考下2018-08-08
我在七夕佳节用Python制作的表白神器,程序员也应该拥有爱情!建议收藏
这篇文章主要介绍了我在七夕佳节用Python制作的表白神器,建议收藏,程序员也该拥有爱情,感兴趣的小伙伴快来看看吧2021-08-08
python使用requests+excel进行接口自动化测试的实现
在当今的互联网时代中,接口自动化测试越来越成为软件测试的重要组成部分,本文就来介绍了python使用requests+excel进行接口自动化测试的实现,感兴趣的可以了解一下2023-11-11
Python常见的2种运行方式:Python Shell和IDLE
Python支持多种运行方式,本文主要介绍了Python常见的2种运行方式:Python Shell和IDLE,文中通过图文示例介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2025-02-02


最新评论