如何在 Python 中将 SVG 转换为 PNG 或 JPEG? [英] How to convert SVG to PNG or JPEG in Python?
问题描述
我正在使用 svgwrite
并生成 svg 文件,如何将它们转换为 PNG 或 JPEG?
I'm using svgwrite
and generating svg-files, how do I convert them to PNG or JPEG?
推荐答案
pyvips 支持 SVG 加载.它免费、速度快、占用内存少,适用于 macOS、Windows 和 Linux.
pyvips supports SVG load. It's free, fast, needs little memory, and works on macOS, Windows and Linux.
你可以这样使用它:
import pyvips
image = pyvips.Image.new_from_file("something.svg", dpi=300)
image.write_to_file("x.png")
默认 DPI 为 72,可能有点低,但您可以设置任何您喜欢的 DPI.您可以用显而易见的方式写入 JPG.
The default DPI is 72, which might be a little low, but you can set any DPI you like. You can write to JPG instead in the obvious way.
您也可以像这样按您想要的像素尺寸加载:
You can also load by the pixel dimensions you want like this:
import pyvips
image = pyvips.Image.thumbnail("something.svg", 200, height=300)
image.write_to_file("x.png")
这将渲染 SVG 以适应 200 x 300 像素的框.文档介绍了所有选项.
That will render the SVG to fit within a 200 x 300 pixel box. The docs introduce all the options.
pyvips SVG 加载器有一些不错的特性:
The pyvips SVG loader has some nice properties:
- 它使用 librsvg 进行实际渲染,因此 PNG 将具有高质量的抗锯齿边缘.
- 它比 ImageMagick 之类的系统快得多,后者只是简单地使用inkscape 进行渲染.
- 它支持渐进式渲染.大图像(每边超过几千像素)是分段渲染的,即使对于非常大的图像,也可以控制内存使用.
- 它支持流式传输,因此您可以将 SVG 直接渲染到一个巨大的 Deep Zoom 金字塔(例如),而无需任何中间存储.
- 它支持来自内存区域、字符串和管道以及文件的输入.
从字符串渲染可以很方便,例如:
Rendering from strings can be handy, eg.:
import pyvips
x = pyvips.Image.svgload_buffer(b"""
<svg viewBox="0 0 200 200">
<circle r="100" cx="100" cy="100" fill="#900"/>
</svg>
""")
x.write_to_file("x.png")
这篇关于如何在 Python 中将 SVG 转换为 PNG 或 JPEG?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!