图片格式转换可以利用各种软件
今天介绍一下如何使用 Python
实现各种图片格式的转换
1. SVG 转其他格式
读取 SVG
格式文件,需要安装 svglib
库
pip install svglib
将 SVG
图片保存为其他格式图片需要用到 reportlab
库
pip install reportlab
1.1 读取 SVG 图片
from svglib.svglib import svg2rlg
drawing = svg2rlg("circos.svg")
1.2 SVG 转 PNG
from reportlab.graphics import renderPM
from svglib.svglib import svg2rlg
drawing = svg2rlg("circos.svg")
renderPM.drawToFile(drawing, "circos.png", fmt="PNG")
1.3 SVG 转 PDF
from reportlab.graphics import renderPDF
from svglib.svglib import svg2rlg
drawing = svg2rlg("circos.svg")
renderPDF.drawToFile(drawing, "circos.pdf")
1.4 SVG 转其他格式
renderPM.drawToFile(
d,
fn,
fmt='GIF',
dpi=72,
bg=16777215,
configPIL=None,
showBoundary=,
)
可以通过设置 fmt 来选择输出格式,
fmt 支持:
'GIF', 'TIFF','TIFFP','TIFFL','TIF','TIFF1' 'PNG','BMP', 'PPM', 'JPG','JPEG'
2. PNG 转其他格式
读取 PNG
图片 使用到了 Pillow
库
pip install Pillow
2.1 PNG 转 JPG
from PIL import Image
img = Image.open('circos.png')
img.save(r'pil_circos.jpg')
2.2 PNG 转 SVG
def toSVG(infile, outfile):
image = Image.open(infile).convert('RGBA')
data = image.load()
width, height = image.size
out = open(outfile, "w")
out.write('\n')
out.write('\n')
out.close()
toSVG('heart.jpeg', 'heart.svg')
2.3 PNG 转 PDF
from PIL import Image
img = Image.open('circos.png')
img.convert('RGB')
img.save('pil_circos.pdf')
2.4 多个 PNG 合并为 PDF
path = 'png file path'
img_list = [Image.open(os.path.join(path, f)).convert('RGB') for f in os.listdir(path)
if f.lower().endswith('png')]
img = img_list.pop(0)
img.save('pil_circos.pdf', resolution=10.0, save_all=True, append_images=img_list)
这种方法会损失分辨率
3. JPG
JPG
或者说 JPEG
的转换与 PNG
格式相同,上面的代码可以复用。
4. 合并多个 PDF 文件
使用到 PyPDF2
库
pip install PyPDF2
使用
from PyPDF2 import PdfFileMerger
import os
path = 'path of pdf file'
pdf_list = [f for f in os.listdir(path) if f.lower().endswith('pdf')]
pdf_merge = PdfFileMerger()
for f in pdf_list:
pdf_merge.append(f)
pdf_merge.write('merge_pdf.pdf')
可以将每张图片先转换为单个 PDF
文件,然后合并 PDF
文件,避免分辨率损失。