我有一个定义为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

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


当前回答

在Linux上用Inkscape 1.0将svg转换为png需要使用

inkscape -w 1024 -h 1024 input.svg --export-file output.png

not

inkscape -w 1024 -h 1024 input.svg --export-filename output.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单位不是px(例如cm)时,Inkscape似乎无法工作。我得到一个空白图像。也许,它可以通过旋转dpi来修复,但它太麻烦了。

Svgexport是一个node.js程序,所以通常不太有用。

Imagemagick的转换工作正常:

 convert -background none -size 1024x1024 infile.svg outfile.png

如果您使用-resize,图像是模糊的,文件是大得多。

BEST

rsvg-convert -w 1024 -h 1024 infile.svg -o outfile.png

它速度最快,依赖性最小,输出比convert小30%左右。安装librsvg2-bin获取:

sudo apt install -y librsvg2-bin

似乎没有手册页,但你可以输入:

rsvg-convert --help

去寻求帮助。简单就是好。

为什么不试试inkscape命令行,这是我的bat文件,将所有SVG在这个目录转换为png:

●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●●

这不是完美的,但它做到了。

convert -density 1200 -resize 200x200 source.svg target.png

基本上,它增加了足够高的DPI(只是使用一个有根据的/安全的猜测),调整大小是有足够质量的。我试图找到一个合适的解决方案,但过了一段时间后,我认为这已经足够满足我目前的需求了。

注意:使用200x200!强制执行给定的决议

我通过更改<svg>标记的宽度和高度属性来匹配我预期的输出大小,然后使用ImageMagick进行转换,从而解决了这个问题。效果非常好。

下面是我的Python代码,一个将返回JPG文件内容的函数:

import gzip, re, os
from ynlib.files import ReadFromFile, WriteToFile
from ynlib.system import Execute
from xml.dom.minidom import parse, parseString


def SVGToJPGInMemory(svgPath, newWidth, backgroundColor):

    tempPath = os.path.join(self.rootFolder, 'data')
    fileNameRoot = 'temp_' + str(image.getID())

    if svgPath.lower().endswith('svgz'):
        svg = gzip.open(svgPath, 'rb').read()
    else:
        svg = ReadFromFile(svgPath)

    xmldoc = parseString(svg)

    width = float(xmldoc.getElementsByTagName("svg")[0].attributes['width'].value.split('px')[0])
    height = float(xmldoc.getElementsByTagName("svg")[0].attributes['height'].value.split('px')[0])

    newHeight = int(newWidth / width * height) 

    xmldoc.getElementsByTagName("svg")[0].attributes['width'].value = '%spx' % newWidth
    xmldoc.getElementsByTagName("svg")[0].attributes['height'].value = '%spx' % newHeight

    WriteToFile(os.path.join(tempPath, fileNameRoot + '.svg'), xmldoc.toxml())
    Execute('convert -background "%s" %s %s' % (backgroundColor, os.path.join(tempPath, fileNameRoot + '.svg'), os.path.join(tempPath, fileNameRoot + '.jpg')))

    jpg = open(os.path.join(tempPath, fileNameRoot + '.jpg'), 'rb').read()

    os.remove(os.path.join(tempPath, fileNameRoot + '.jpg'))
    os.remove(os.path.join(tempPath, fileNameRoot + '.svg'))

    return jpg