在日常生活中,经常会遇到需要提交身份证正反面证明资料的情况,而且这些网站大部分只接受pdf格式,这时候我们就需要把身份证正反面两张图片合成为一个pdf文件。
网上有很多合成PDF的网站,但是这些网站无一例外需要上传PDF进行合成,个人认为非常地不安全。
因此,最安全的方法,还是我们自己写一个Python脚本实现合成功能。
1.准备
输入命令安装依赖
pip install pillow -i https://pypi.mirrors.ustc.edu.cn/simple/
2.合成原理
Pillow模块,即PIL:Python Imaging Library,已经是Python平台事实上的图像处理标准库了。PIL功能非常强大,但API却非常简单易用。通过它,我们能很轻松地操作图像,并导出为不同格式。
首先来一个简单的示例,我们将打开一张图片,并将其保存为pdf格式:
源码如下:
from PIL import Image
import os
def convert_img_pdf(filepath, output_path):
"""
转换图片为pdf格式
Args:
filepath (str): 文件路径
output_path (str): 输出路径
"""
output = Image.open(filepath)
output.save(output_path, "pdf", save_all=True)
if __name__ == "__main__":
convert_img_pdf("1.jpeg","test.pdf")
3.多张照片合成PDF
有了前面照片转化PDF的基础知识,想要理解下面的多图合成PDF的代码就非常简单了。
其实就是使用了.save的一个特殊参数 append_images:
output.save(pdfFilePath, "pdf", save_all=True, append_images=sources)
通过把图片都存入到一个"sources"数组中,我们就能很轻易地合成这些图像到PDF中。
我们将同文件夹下图片合成一个PDF。
源码如下:
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 17 10:57:40 2023
@author: Admin
"""
import os
import time
from PIL import Image
cmd='echo "%cd%" > 6.txt'
os.system(cmd)
time.sleep(6)
f = open("6.txt", 'r', encoding="gb2312")
directory_path = f.read()[1:-3]
f.close()
#directory_path = os.path.dirname(os.path.abspath(__file__))
print(directory_path)
ran=[]
for file_name in os.listdir(directory_path):
#后缀判断
if file_name.endswith('.png') or file_name.endswith('.jpg'):
print(file_name)
ran.append(file_name)
im = Image.open(ran[0])
im=im.convert('RGB')
im_list=[]
for i in range(1,len(ran)):
im_list.append(Image.open(ran[i]).convert('RGB'))
#tn=time.strftime('%Y%m%d%H%M%S',time.gmtime())
tn=time.strftime('%Y%m%d%H%M%S',time.localtime())
im.save("%s.pdf"%tn, "PDF", resolution=100.0, save_all=True, append_images=im_list)
print("成功生成'%s.pdf'文件"%tn)
os.remove("6.txt")
print("成功删除6.txt")
t=time.strftime("%Y{}%m{}%d{}", time.localtime())
t=t.format("年","月","日")
print(t)
4.多张照片反色合成PDF
原理:ImageChops.invert(img)或ImageOps.invert(img)
源码如下:
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 17 10:57:40 2023
@author: Admin
"""
import os
import time
from PIL import Image,ImageChops
cmd='echo "%cd%" > 6.txt'
os.system(cmd)
time.sleep(6)
f = open("6.txt", 'r', encoding="gb2312")
directory_path = f.read()[1:-3]
f.close()
#directory_path = os.path.dirname(os.path.abspath(__file__))
print(directory_path)
ran=[]
for file_name in os.listdir(directory_path):
#后缀判断
if file_name.endswith('.png') or file_name.endswith('.jpg'):
print(file_name)
ran.append(file_name)
im=ImageChops.invert(Image.open(ran[0]).convert('RGB'))
im_list=[]
for i in range(1,len(ran)):
im_list.append(ImageChops.invert(Image.open(ran[i]).convert('RGB')))
#tn=time.strftime('%Y%m%d%H%M%S',time.gmtime())
tn=time.strftime('%Y%m%d%H%M%S',time.localtime())
im.save("%s.pdf"%tn, "PDF", resolution=100.0, save_all=True, append_images=im_list)
print("成功生成'%s.pdf'文件"%tn)
os.remove("6.txt")
print("成功删除6.txt")
t=time.strftime("%Y{}%m{}%d{}", time.localtime())
t=t.format("年","月","日")
print(t)
2698



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



