Python 把两张图片拼起来

该博客介绍了如何在Linux系统中使用Python的PIL库将两张图片拼接在一起。通过编写`combine.py`和`main.py`两个脚本,实现了读取指定文件夹中的图片,检查它们的尺寸并进行适当拼接,最后保存到特定目录的功能。脚本适用于批量处理同一尺寸的图片,并生成新的组合图片。

 Linux系统下使用 Python 把两张图片拼起来

 combine.py

from PIL import Image
from os import listdir, chdir, mkdir
from os.path import isfile


def combine(pic1_file, pic2_file, output=None):
    img1 = Image.open(pic1_file)
    img2 = Image.open(pic2_file)
    if (img1.height != img2.height) or (img1.width != img2.width):
        pass #回头再说
        print("两张图片宽高不匹配!")
        return 1
    if not output:
        output = 'output.png'
    padding =  20
    height = img1.height + padding * 2
    width = img1.width * 2 + padding * 3
    img3 = Image.new('RGB', (width, height), (255, 255, 255))
    #创建了一个图像,尺寸预留留白空间
    img3.paste(img1, (padding, padding))
    img3.paste(img2, (padding*2+img1.width, padding))
    img3.save(output)
    img1.close()
    img2.close()
    img3.close()
    return 0
    


if __name__ == '__main__':
    chdir("/home/xxc/桌面/pic")
    dirs = listdir()
    if "Output" not in dirs:
        mkdir("Output")
    from pathlib import Path
    output = Path(Path.cwd() / "Output" / "output.jpg")
    combine("0.png", "000.png", output)

 main.py

from combine import combine
from os import chdir
from pathlib import Path



def do_something(file1, file2, output_file):
    #执行的动作
    combine(file1, file2, output_file)



def iter_folder(path1, path2, output_path):
    files1 = [x for x in path1.iterdir() if x.is_file()]
    files2 = [x for x in path2.iterdir() if x.is_file()]
    for file1 in files1:
        file2 = path2 / file1.name
        if file2 in files2:
            output_file = output_path / "{}_{}.{}".format(path1.name, file1.stem, "jpg")
            do_something(file1, file2, output_file)



if __name__ == '__main__':
    chdir("/home/xxc/桌面/pic")
    path1 = Path.cwd() / "原图"
    path2 = Path.cwd() / "处理好"
    output_path = Path.cwd() / "Output"
    for i in range(7):
        iter_folder(path1/str(i+1), path2/str(i+1), output_path)

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

浅羽三千

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值