python3,基于Pillow的图片合成

背景:想将多张图片合成一张,且不改变图片的大小

思路:读取某个文件夹下所有的图片,主要是jpg跟png,然后计算需要合成图片的大小(既每行几张,每列几张,然后将这些图片的长宽累加起来),最后进行图片拼接。

以下是具体代码:

import os
from natsort import os_sorted
from PIL import Image


def merge_images(output_file, n, m):
	# 从txt文件中读取路径 image_path.txt 存放的是图片所在文件夹的路径
    folder = open('./image_path.txt', encoding='utf-8')
    image_folder = folder.readline()
    # 获取所有图像文件的列表
    image_files = [os.path.join(image_folder, f) for f in os_sorted(os.listdir(image_folder)) if (f.endswith('.jpg') or f.endswith('.png'))]

    image_count = len(image_files)
    if image_count == 0:
        return

    new_img_gao = 0
    # 合成后,每张图片的高度
    gao = []

    for i, f in enumerate(image_files):
        img = Image.open(f)
        new_img_gao += img.size[1]
        if (i + 1) % 3 == 0:
            gao.append(new_img_gao)
            new_img_gao = 0

    # 创建一个新的大图像 这边固定800  按需要调整,可以参考gao设置方式,进行动态设置
    new_img = Image.new('RGB', (800*n, gao[0]), 'white')
    # 合成一张长图片  保存一次
    count = n * m
    resultCount = 0
    row = 0
    # 将所有小图像粘贴到新图像的正确位置
    for i, f in enumerate(image_files):
        img = Image.open(f)
        new_img.paste(img, (0, row))
        row += img.size[1]
        count = count - 1
        if 0 == count:
            row = 0
            resultCount = resultCount + 1
            # 保存大图像
            new_img.save(image_folder + '\m' + str(i) + output_file)
            if len(gao) > resultCount:
                new_img = Image.new('RGB', (800*n, gao[resultCount]), 'white')
            else:
                return
            count = n * m


# 单行,三列,合成长图片
output_file = 'output.jpg'
n = 1  # 每行显示的图像数
m = 3  # 每列显示的图像数
if __name__ == '__main__':
    merge_images(output_file, n, m)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值