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

被折叠的 条评论
为什么被折叠?



