Python 多張圖片合并成一個(gè)pdf的參考示例
過程
拿到一個(gè)需求最重要的就是將大塊任務(wù)拆分成一個(gè)個(gè)小模塊,逐個(gè)擊破。
拍照
這一步首先是將所有的書頁拍好,需要注意的是要按照書的頁碼來拍,因?yàn)楹竺娴呐判蚴前凑瘴募M(jìn)行排序的,拍照的文件名基本上是按照時(shí)間生成的,如果拍的時(shí)候亂了,到時(shí)候生成的 pdf 里面的頁碼也會(huì)亂掉。
用到的Python 操作庫
Python 最好的地方就是有大量的第三方庫能幫我們快速實(shí)現(xiàn)我們想要的方法,搜索到了兩個(gè)庫, PyFPDF 和img2pdf,我們這里選擇img2pdf來完成我們的需求 pip install img2pdf
Python遍歷文件夾獲取圖片
dirname = "f:/wlzcool"
imgs = []
for fname in os.listdir(dirname):
if not fname.endswith(".jpg"):
continue
path = os.path.join(dirname, fname)
if os.path.isdir(path):
continue
imgs.append(path)
需要注意圖片的文件名如果是純數(shù)字且位數(shù)不一樣,排序會(huì)為1之后是10而不是2,需要進(jìn)行一個(gè)排序,如果是手機(jī)拍的文件就沒有這個(gè)問題。 files.sort(key=lambda x: int(x[:-4]))
旋轉(zhuǎn)圖片展示方向并壓縮像素
有的時(shí)候手機(jī)拍出來的圖片是水平的,需要將其改為豎直的
用rotate旋轉(zhuǎn)方向的時(shí)候需要注意加上expand=True 這個(gè)參數(shù),否則會(huì)有黑邊出現(xiàn)。
手機(jī)的照片像素太高,有的需要進(jìn)行壓縮以保證最后生成的pdf的大小適中。
img = Image.open(path)
if img.size[0] > img.size[1]:
im_rotate = img.rotate(90, expand=True)
size = (int(im_rotate.size[0] / 3), int(im_rotate.size[1] / 3))
im_rotate = im_rotate.resize(size)
im_rotate.save(savepath, quality=95)
else:
size = (int(img.size[0] / 3), int(img.size[1] / 3))
img = img.resize(size)
img.save(savepath, quality=95)
整體代碼
寫成腳本需要考慮的有很多,為了方便使用,需要將各種參數(shù)改為允許用戶輸入的。比如圖片文件夾所在的路徑,壓縮比之類的
from PIL import Image
import os
import img2pdf
flag = False
while not flag:
dirname = input("請(qǐng)輸入圖片文件夾所在路徑(例如d:/wlzcool):")
flag = os.path.exists(dirname)
if not flag:
print("圖片文件夾所在路徑不存在!")
saveflag = False
while not saveflag:
savedirname = input("請(qǐng)輸入目標(biāo)圖片文件夾所在路徑(例如d:/wlzcool2):")
saveflag = os.path.exists(savedirname)
if not saveflag:
print("圖片文件夾所在路徑不存在!")
automakedir = input("是否自動(dòng)創(chuàng)建對(duì)應(yīng)文件夾?(是Y/否N):")
if automakedir.strip().upper() == "Y":
os.makedirs(savedirname)
saveflag = True
files = os.listdir(dirname)
reductionFactor = int(input("請(qǐng)輸入長(zhǎng)寬壓縮比(例如3):"))
if reductionFactor <= 0:
reductionFactor = 3
isConvertBlack = input("是否輸出黑白版本?(是Y/否N):").strip().upper() == "Y"
for fname in files:
if not fname.endswith(".jpg"):
continue
path = os.path.join(dirname, fname)
savePath = os.path.join(savedirname, fname)
if os.path.isdir(path):
continue
img = Image.open(path)
if img.size[0] > img.size[1]:
im_rotate = img.rotate(90, expand=True)
size = (int(im_rotate.size[0] / reductionFactor), int(im_rotate.size[1] / reductionFactor))
im_rotate = im_rotate.resize(size)
if isConvertBlack:
im_rotate = im_rotate.convert("L")
im_rotate.save(savePath, quality=95)
else:
size = (int(img.size[0] / reductionFactor), int(img.size[1] / reductionFactor))
img = img.resize(size)
if isConvertBlack:
img = img.convert("L")
img.save(savePath, quality=95)
filename = input("請(qǐng)輸入輸出文件名(例如:第一章):")
with open(filename + ".pdf", "wb") as f:
imgs = []
files = os.listdir(savedirname)
for fname in files:
if not fname.endswith(".jpg"):
continue
path = os.path.join(savedirname, fname)
if os.path.isdir(path):
continue
imgs.append(path)
f.write(img2pdf.convert(imgs))
整體代碼
寫成腳本需要考慮的有很多,為了方便使用,需要將各種參數(shù)改為允許用戶輸入的。比如圖片文件夾所在的路徑,壓縮比之類的
from PIL import Image
import os
import img2pdf
flag = False
while not flag:
dirname = input("請(qǐng)輸入圖片文件夾所在路徑(例如d:/wlzcool):")
flag = os.path.exists(dirname)
if not flag:
print("圖片文件夾所在路徑不存在!")
saveflag = False
while not saveflag:
savedirname = input("請(qǐng)輸入目標(biāo)圖片文件夾所在路徑(例如d:/wlzcool2):")
saveflag = os.path.exists(savedirname)
if not saveflag:
print("圖片文件夾所在路徑不存在!")
automakedir = input("是否自動(dòng)創(chuàng)建對(duì)應(yīng)文件夾?(是Y/否N):")
if automakedir.strip().upper() == "Y":
os.makedirs(savedirname)
saveflag = True
files = os.listdir(dirname)
reductionFactor = int(input("請(qǐng)輸入長(zhǎng)寬壓縮比(例如3):"))
if reductionFactor <= 0:
reductionFactor = 3
isConvertBlack = input("是否輸出黑白版本?(是Y/否N):").strip().upper() == "Y"
for fname in files:
if not fname.endswith(".jpg"):
continue
path = os.path.join(dirname, fname)
savePath = os.path.join(savedirname, fname)
if os.path.isdir(path):
continue
img = Image.open(path)
if img.size[0] > img.size[1]:
im_rotate = img.rotate(90, expand=True)
size = (int(im_rotate.size[0] / reductionFactor), int(im_rotate.size[1] / reductionFactor))
im_rotate = im_rotate.resize(size)
if isConvertBlack:
im_rotate = im_rotate.convert("L")
im_rotate.save(savePath, quality=95)
else:
size = (int(img.size[0] / reductionFactor), int(img.size[1] / reductionFactor))
img = img.resize(size)
if isConvertBlack:
img = img.convert("L")
img.save(savePath, quality=95)
filename = input("請(qǐng)輸入輸出文件名(例如:第一章):")
with open(filename + ".pdf", "wb") as f:
imgs = []
files = os.listdir(savedirname)
for fname in files:
if not fname.endswith(".jpg"):
continue
path = os.path.join(savedirname, fname)
if os.path.isdir(path):
continue
imgs.append(path)
f.write(img2pdf.convert(imgs))
將腳本打包成exe
不是所有的電腦都有Python環(huán)境,我們需要將腳本打包成exe方便在任意一臺(tái)電腦上使用。 使用 PyInstaller 來進(jìn)行腳本的打包
安裝 PyInstaller
pip install pyinstaller
打包腳本
在腳本所在的路徑的cmd中執(zhí)行以下命令即可
pyinstaller -F yourprogram.py
總結(jié)
人生苦短,我用 Python,在強(qiáng)大的第三方庫幫助下,我們只需很少的時(shí)間就可以開發(fā)一個(gè)很有意思的小功能。
以上就是Python 多張圖片合并成一個(gè)pdf的參考示例的詳細(xì)內(nèi)容,更多關(guān)于Python 圖片合并成pdf的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
使用Python代碼識(shí)別股票價(jià)格圖表模式實(shí)現(xiàn)
這篇文章主要為大家介紹了使用Python代碼識(shí)別股票價(jià)格圖表模式的實(shí)現(xiàn)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-12-12
Python如何將LabelMe生成的JSON格式轉(zhuǎn)換成YOLOv8支持的TXT格式
標(biāo)注工具 LabelMe 生成的標(biāo)注文件為JSON格式,而YOLOv8中支持的為TXT文件格式,下面給大家分享Python如何將LabelMe生成的JSON格式轉(zhuǎn)換成YOLOv8支持的TXT格式,感興趣的朋友跟隨小編一起看看吧2024-05-05
在python中以相同順序shuffle兩個(gè)list的方法
今天小編就為大家分享一篇在python中以相同順序shuffle兩個(gè)list的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-12-12
Python實(shí)現(xiàn)Kerberos用戶的增刪改查操作
這篇文章主要介紹了Python實(shí)現(xiàn)Kerberos用戶的增刪改查操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-12-12
淺談Pandas dataframe數(shù)據(jù)處理方法的速度比較
這篇文章主要介紹了淺談Pandas dataframe數(shù)據(jù)處理方法的速度比較,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2021-04-04
python連接手機(jī)自動(dòng)搜集螞蟻森林能量的實(shí)現(xiàn)代碼
這篇文章主要介紹了python連接手機(jī)自動(dòng)搜集螞蟻森林能量的實(shí)現(xiàn)方法,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-02-02
Pycharm中如何關(guān)掉python console
這篇文章主要介紹了Pycharm中如何關(guān)掉python console,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-10-10
使用SimpleITK讀取NII格式三維圖像及注意事項(xiàng)說明
這篇文章主要介紹了使用SimpleITK讀取NII格式三維圖像及注意事項(xiàng)說明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-12-12

