美文网首页PythonPython
Python 图片格式转换

Python 图片格式转换

作者: 名本无名 | 来源:发表于2020-12-11 17:18 被阅读0次

图片格式转换可以利用各种软件

今天介绍一下如何使用 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=<reportlab.rl_config._unset_ object at 0x106458070>,
)
可以通过设置 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('<?xml version="1.0" encoding="UTF-8" standalone="no"?>\n')
    out.write('<svg id="svg2" xmlns="http://www.w3.org/2000/svg" version="1.1" \
                width="%(x)i" height="%(y)i" viewBox="0 0 %(x)i %(y)i">\n' % \
              {'x': width, 'y': height})
    
    for y in range(height):
        for x in range(width):
            rgba = data[x, y]
            rgb = '#%02x%02x%02x' % rgba[:3]
            if rgba[3] > 0:
                out.write('<rect width="1" height="1" x="%i" y="%i" fill="%s" \
                    fill-opacity="%.2f" />\n' % (x, y, rgb, rgba[3]/255.0))
    out.write('</svg>\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 文件,避免分辨率损失。

相关文章

网友评论

    本文标题:Python 图片格式转换

    本文链接:https://www.haomeiwen.com/subject/sumjgktx.html