python使用PIL实现多张图片垂直合并

yipeiwu_com5年前Python基础

本文实例为大家分享了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的Django框架中生成CSV文件的方法

CSV 是一种简单的数据格式,通常为电子表格软件所使用。 它主要是由一系列的表格行组成,每行中单元格之间使用逗号(CSV 是 逗号分隔数值(comma-separated values)...

Python随机生成数模块random使用实例

代码 复制代码 代码如下: #!/usr/bin/env python #coding=utf-8 import random #生成[0, 1)直接随机浮点数 print random...

python+matplotlib实现动态绘制图片实例代码(交互式绘图)

python+matplotlib实现动态绘制图片实例代码(交互式绘图)

本文研究的主要是python+matplotlib实现动态绘制图片(交互式绘图)的相关内容,具体介绍和实现代码如下所示。   最近在研究动态障碍物避障算法,在Python语言进行算法仿真...

用python求一个数组的和与平均值的实现方法

如下所示: # coding = GBK a =[1,2,3,4,5] sum=0 b = len(a) print("这个数组的长度为:",b) for i in a:...

使用Python编写简单的画图板程序的示例教程

使用Python编写简单的画图板程序的示例教程

从这次开始,我会由简单到困难(其实也不会困难到哪里去)讲几个例程,每一个例程都是我自己写(或者修改,那样的话我会提供原始出处)的,都具有一定的操作性和娱乐性。例程中汇尽量覆盖到以前所讲的...