Python小工具,長圖另存為pdf
阿新 • • 發佈:2018-11-11
在網上了一個長的圖片,結果發現沒有一個合適的工具,將長圖先批量擷取為4:3格式,儲存到指定地點,然後儲存為pdf
程式碼:
from reportlab.lib.pagesizes import portrait from reportlab.pdfgen import canvas import os from PIL import Image # 按照3:4 分割圖片,返回圖片儲存結果集 def splitimage(src, dstpath): img = Image.open(src) w, h = img.size height=w*4/3 #3:4比例出的高度,等比縮放,算出高度 height_dim = w*4/3 # 記錄一個固定值,方便後期呼叫 print(height) num=h/height# 分割次數 print(num) index=0 s = os.path.split(src)#分割出路徑和檔名 if dstpath == '': dstpath = s[0] fn = s[1].split('.') basename = fn[0]#檔名 postfix = fn[-1]#字尾名 img_urls=[] while (index < num): print('Index is:', index," Height is ",height) box = (0, height-height_dim, w, height) img.crop(box).save(os.path.join(dstpath, basename + '_' + str(index) + '.' + postfix), img.format) img_urls.append(os.path.join(dstpath, basename + '_' + str(index) + '.' + postfix)) height = height+height_dim index = index + 1 return img_urls # 零散,大小一致圖片,儲存為pdf def imgtopdf(input_paths, outputpath): index=0 # 取一個大小 (maxw, maxh) = Image.open(input_paths[0]).size c = canvas.Canvas(outputpath, pagesize=portrait((maxw, maxh))) for ont_path in input_paths : c.drawImage(ont_path, 0, 0, maxw, maxh) c.showPage() index=index+1 c.save() src="D:\\xvshu\\高數\\線性代數資料\\測試.png" dstpath="D:\\xvshu\\高數\\線性代數資料\\" imgs = splitimage(src, dstpath) print(imgs) # 呼叫demo: imgtopdf(imgs, "D:\\xvshu\\高數\\線性代數資料\\測試.pdf") print("over")