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

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


当前回答

我通过更改<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

其他回答

我来到这个帖子-但我只是想做批量和快速的转换,而不使用任何参数(由于几个文件大小不同)。

rsvg drawing.svg drawing.png

对我来说,这些要求可能比原作者要简单一些。(想在MS PowerPoint中使用SVGs,但它不允许)

如果你在MacOS X上,Imagemagick的转换有问题,你可以尝试用RSVG库重新安装它。 使用自制程序:

brew remove imagemagick
brew install imagemagick --with-librsvg

验证它是否正确地委托:

$ convert -version
Version: ImageMagick 6.8.9-8 Q16 x86_64 2014-12-17 http://www.imagemagick.org
Copyright: Copyright (C) 1999-2014 ImageMagick Studio LLC
Features: DPC Modules
Delegates: bzlib cairo fontconfig freetype jng jpeg lcms ltdl lzma png rsvg tiff xml zlib

它应该显示rsvg。

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

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

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

在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

如果没有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