我有一个定义为16x16大小的SVG文件。当我使用ImageMagick的转换程序将其转换为PNG时,我得到了一个16x16像素的PNG,太小了:

convert test.svg test.png

我需要指定输出PNG的像素大小。-size parameter似乎被忽略了,-scale parameter在PNG被转换成PNG后缩放。到目前为止,我使用-density参数得到的最好结果是:

convert -density 1200 test.svg test.png

但我并不满意,因为我想指定以像素为单位的输出大小,而不做数学运算来计算密度值。所以我想这样做:

convert -setTheOutputSizeOfThePng 1024x1024 test.svg test.png

这里我要用到的神奇参数是什么?


当前回答

这对我来说是最有效的,也是最容易运行的。

find . -type f -name "*.svg" -exec bash -c 'rsvg-convert -h 1000  $0 > $0.png' {} \;
rename 's/svg\.png/png/' *

这将循环当前文件夹和子文件夹中的所有文件,寻找.svg文件,并将其转换为透明背景的png。

确保已经安装了librsvg并重命名了util

brew install librsvg
brew install rename

其他回答

对于简单的SVG到PNG转换,我发现cairosvg (https://cairosvg.org/)比ImageMagick执行得更好。安装和运行目录中所有SVG文件的步骤。

pip3 install cairosvg

在包含.svg文件的目录中打开一个python shell,然后运行:

import os
import cairosvg

for file in os.listdir('.'):
    name = file.split('.svg')[0]
    cairosvg.svg2png(url=name+'.svg',write_to=name+'.png') 

这也将确保您不会覆盖原始的.svg文件,但将保持相同的名称。然后你可以移动你所有的。png文件到另一个目录:

$ mv *.png [new directory]

如果没有librsvg,你可能会得到一个黑色的png/jpeg图像。我们必须安装librsvg转换svg文件与imagemagick。

Ubuntu

 sudo apt-get install imagemagick librsvg
 convert -density 1200 test.svg test.png

操作系统

 brew install imagemagick librsvg
 convert -density 1200 test.svg test.png

在使用brew的macOS上,直接使用librsvg效果很好

brew install librsvg
rsvg-convert test.svg -o test.png

通过rsvg-convert——help可以获得许多选项

为了重新缩放图像,应该使用-density选项。据我所知,标准密度是72,对应尺寸为1:1。如果你想要输出png是原始svg的两倍大,将密度设置为72*2=144:

convert -density 144 source.svg target.png

在这个例子中,我还没有能够从ImageMagick得到很好的结果,但Inkscape在Linux和Windows上缩放SVG方面做得很好:

# Inkscape v1.0+
inkscape -w 1024 -h 1024 input.svg -o output.png
# Inkscape older than v1.0
inkscape -z -w 1024 -h 1024 input.svg -e output.png

注意,您可以省略一个宽度/高度参数,让另一个参数根据输入图像尺寸自动缩放。

下面是使用这个命令将16x16的SVG缩放为200x200的PNG的结果: