python使用PIL实现多张图片垂直合并
Python  /  管理员 发布于 7年前   170
本文实例为大家分享了python实现多张图片垂直合并的具体代码,供大家参考,具体内容如下
# coding: utf-8 # image_merge.py # 图片垂直合并 # http://www.redicecn.com # [email protected] 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'])
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
122 在
学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..123 在
Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..原梓番博客 在
在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..博主 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..1111 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
Copyright·© 2019 侯体宗版权所有·
粤ICP备20027696号