如何将SVG转换成具有图像效果的PNG ?

时间:2022-08-21 09:00:02

I have a SVG file which has a defined size of 16x16. When I use Image Magick's convert program to convert it into a PNG then I get a 16x16 pixel PNG which is way too small:

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

convert test.svg test.png

I need to specify the pixel size of the output PNG. -size parameter seems to be ignored, -scale parameter scales the PNG after it has been converted to PNG. The best result up to now I got by using the -density parameter:

我需要指定输出的像素大小PNG。参数似乎被忽略,剂量参数尺度PNG后转换为PNG。最好的结果到目前为止我通过使用密度参数:

convert -density 1200 test.svg test.png

But I'm not satisfied because I want to specify the output size in pixels without doing math to calculate the density value. So I want to do something like this:

但我不满足,因为我想指定的输出大小不做数学计算像素密度值。所以我想这样做:

convert -setTheOutputSizeOfThePng 1024x1024 test.svg test.png

So what is the magic parameter I have to use here?

那么我要用什么神奇的参数呢?

13 个解决方案

#1


333  

I haven't been able to get good results from ImageMagick in this instance, but Inkscape does a nice job of it on Linux and Windows:

我没能得到好的结果来自ImageMagick在这个实例中,但是Inkscape做一个好的它在Linux和Windows的工作:

inkscape -z -e test.png -w 1024 -h 1024 test.svg

Here's the result of scaling a 16x16 SVG to a 200x200 PNG using this command:

下面是使用这个命令将16x16 SVG扩展到200x200 PNG的结果:

如何将SVG转换成具有图像效果的PNG ?

如何将SVG转换成具有图像效果的PNG ?

Just for reference, my Inkscape version (on Ubuntu 12.04) is:

作为参考,我的Inkscape版本(Ubuntu 12.04)是:

Inkscape 0.48.3.1 r9886 (Mar 29 2012)

and on Windows 7, it is:

在Windows 7上,它是:

Inkscape 0.48.4 r9939 (Dec 17 2012)

#2


91  

Try svgexport:

试试svgexport:

svgexport input.svg output.png 64x
svgexport input.svg output.png 1024:1024

svgexport is a simple cross-platform command line tool that I have made for exporting svg files to jpg and png, see here for more options. To install svgexport install npm, then run:

svgexport是一个简单的跨平台命令行工具,我将svg文件导出到jpg和png中,请参阅这里的更多选项。要安装svgexport安装npm,请运行:

npm install svgexport -g

Edit: If you find an issue with the library, please submit it on GitHub, thanks!

编辑:如果你发现图书馆有问题,请在GitHub上提交,谢谢!

#3


72  

This is not perfect but it does the job.

这不是完美的,但它确实有效。

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

Basically it increases the DPI high enough (just use an educated/safe guess) that resizing is done with adequate quality. I was trying to find a proper solution to this but after a while decided this was good enough for my current need.

基本上,它增加了足够高的DPI(仅仅使用一个有经验的/安全的猜测),大小调整是用适当的质量完成的。我试图找到一个合适的解决办法,但过了一会儿,我觉得这个办法对我目前的需要来说已经足够了。

Note: Use 200x200! to force the given resolution

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

#4


42  

If you are on MacOS X and having problems with Imagemagick's convert, you might try reinstalling it with RSVG lib. Using HomeBrew:

如果您在MacOS X上,并且在Imagemagick的转换上有问题,您可以尝试使用RSVG lib重新安装它。

brew remove imagemagick
brew install imagemagick --with-librsvg

Verify that it's delegating correctly:

验证是否正确委派:

$ 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

It should display rsvg.

它应该显示rsvg。

#5


20  

Inkscape doesn't seem to work when svg units are not px (e.g. cm). I got a blank image. Maybe, it could be fixed by twiddling the dpi, but it was too troublesome.

当svg单元不是px(例如cm)时,Inkscape似乎就不起作用了。我得到了一个空白的图像。也许,它可以通过玩弄dpi来解决,但它太麻烦了。

Svgexport is a node.js program and so not generally useful.

Svgexport是一个节点。js程序,所以不太有用。

Imagemagick's convert works ok with:

Imagemagick的转换可以使用:

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

If you use -resize, the image is fuzzy and the file is much larger.

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

BEST

请接受我最美好的祝愿,

~$ rsvg  -w 1024 -h 1024 infile.svg  outfile.png

It is fastest, has the fewest dependencies, and the output is about 30% smaller than convert. Install librsvg2-bin to get it. There does not appear to be a man page but you can type:

它是最快的,具有最少的依赖性,并且输出比转换的要小30%左右。安装librsvg2-bin来获取它。似乎没有男人的页面,但你可以打字:

~$ rsvg --help

to get some assistance. Simple is good.

得到一些帮助。简单是好的。

#6


10  

After following the steps in Jose Alban's answer, I was able to get ImageMagick to work just fine using the following command:

按照何塞·阿尔班回答的步骤,我可以使用以下命令让ImageMagick工作得很好:

convert -density 1536 -background none -resize 100x100 input.svg output-100.png

The number 1536 comes from a ballpark estimate of density, see this answer for more information.

数字1536来自密度的估计,更多信息请看这个答案。

#7


8  

In order to rescale the image, the option -density should be used. As far as I know the standard density is 72 and maps the size 1:1. If you want the output png to be as double as big as the original svg set density to 72*2=144

为了重新调整图像的大小,应该使用选项-密度。据我所知,标准密度是72,并映射成1:1。如果您希望输出png的大小是原始svg的两倍,请将密度设置为72*2=144

convert -density 144 source.svg target.png

将密度144源。svg target.png

#8


6  

why don't you give a try to inkscape command line, this is my bat file to convert all svg in this dir to png:

为什么不尝试使用inkscape命令行呢?这是我将这个目录中的svg转换为png的bat文件:

FOR %%x IN (*.svg) DO C:\Ink\App\Inkscape\inkscape.exe %%x -z --export-dpi=500 --export-area-drawing --export-png="%%~nx.png"

为%x IN (*.svg)做C:\Ink\App\Inkscape Inkscape。exe %x -z——export-dpi=500——export-area-draw -export-png="%%~nx.png"

#9


2  

One thing that just bit me was setting the -density AFTER the input file name. That didn't work. Moving it to the first option in convert (before anything else) made it work (for me, YMMV, etc).

有一件事让我很不爽,那就是在输入文件名之后设置-density。没有工作。将它移动到皈依的第一个选项(在其他选项之前)使它工作(对我、YMMV等)。

#10


1  

I came to this post - but I just wanted to do the conversion by batch and quick without the usage of any parameters (due to several files with different sizes).

我来到这篇文章——但是我只是想以批处理和快速的方式进行转换,而不使用任何参数(由于有几个不同大小的文件)。

rsvg drawing.svg drawing.png

For me the requirements were probably a bit easier than for the original author. (Wanted to use SVGs in MS PowerPoint, but it doesn't allow)

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

#11


0  

I've solved this issue through changing the width and height attributes of the <svg> tag to match my intended output size and then converting it using ImageMagick. Works like a charm.

通过更改 标记的宽度和高度属性以匹配预期的输出大小,然后使用ImageMagick对其进行转换,我解决了这个问题。就像一个魅力。

Here's my Python code, a function that will return the JPG file's content:

下面是我的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

#12


0  

For simple SVG to PNG conversion I found cairosvg (https://cairosvg.org/) performs better than ImageMagick. Steps for install and running on all SVG files in your directory.

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

pip3 install cairosvg

Open a python shell in the directory which contains your .svg files and run:

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

import os

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

This will also ensure you don't overwrite your original .svg files, but will keep the same name. You can then move all your .png files to another directory with:

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

$ mv *.png [new directory]

#13


-1  

The top answer by @808sound did not work for me. I wanted to resize 如何将SVG转换成具有图像效果的PNG ?

@808sound给出的最上面的答案对我不起作用。我想调整

and got 如何将SVG转换成具有图像效果的PNG ?

并得到了

So instead I opened up Inkscape, then went to File, Export as PNG fileand a GUI box popped up that allowed me to set the exact dimensions I needed.

所以我打开Inkscape,然后到File中,导出为PNG文件,然后弹出一个GUI框,允许我设置所需的确切尺寸。

Version on Ubuntu 16.04 Linux: Inkscape 0.91 (September 2016)

Ubuntu 16.04 Linux版本:Inkscape 0.91(2016年9月)

(This image is from Kenney.nl's asset packs by the way)

(这张照片来自肯尼。顺便说一下,nl的资产包)

#1


333  

I haven't been able to get good results from ImageMagick in this instance, but Inkscape does a nice job of it on Linux and Windows:

我没能得到好的结果来自ImageMagick在这个实例中,但是Inkscape做一个好的它在Linux和Windows的工作:

inkscape -z -e test.png -w 1024 -h 1024 test.svg

Here's the result of scaling a 16x16 SVG to a 200x200 PNG using this command:

下面是使用这个命令将16x16 SVG扩展到200x200 PNG的结果:

如何将SVG转换成具有图像效果的PNG ?

如何将SVG转换成具有图像效果的PNG ?

Just for reference, my Inkscape version (on Ubuntu 12.04) is:

作为参考,我的Inkscape版本(Ubuntu 12.04)是:

Inkscape 0.48.3.1 r9886 (Mar 29 2012)

and on Windows 7, it is:

在Windows 7上,它是:

Inkscape 0.48.4 r9939 (Dec 17 2012)

#2


91  

Try svgexport:

试试svgexport:

svgexport input.svg output.png 64x
svgexport input.svg output.png 1024:1024

svgexport is a simple cross-platform command line tool that I have made for exporting svg files to jpg and png, see here for more options. To install svgexport install npm, then run:

svgexport是一个简单的跨平台命令行工具,我将svg文件导出到jpg和png中,请参阅这里的更多选项。要安装svgexport安装npm,请运行:

npm install svgexport -g

Edit: If you find an issue with the library, please submit it on GitHub, thanks!

编辑:如果你发现图书馆有问题,请在GitHub上提交,谢谢!

#3


72  

This is not perfect but it does the job.

这不是完美的,但它确实有效。

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

Basically it increases the DPI high enough (just use an educated/safe guess) that resizing is done with adequate quality. I was trying to find a proper solution to this but after a while decided this was good enough for my current need.

基本上,它增加了足够高的DPI(仅仅使用一个有经验的/安全的猜测),大小调整是用适当的质量完成的。我试图找到一个合适的解决办法,但过了一会儿,我觉得这个办法对我目前的需要来说已经足够了。

Note: Use 200x200! to force the given resolution

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

#4


42  

If you are on MacOS X and having problems with Imagemagick's convert, you might try reinstalling it with RSVG lib. Using HomeBrew:

如果您在MacOS X上,并且在Imagemagick的转换上有问题,您可以尝试使用RSVG lib重新安装它。

brew remove imagemagick
brew install imagemagick --with-librsvg

Verify that it's delegating correctly:

验证是否正确委派:

$ 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

It should display rsvg.

它应该显示rsvg。

#5


20  

Inkscape doesn't seem to work when svg units are not px (e.g. cm). I got a blank image. Maybe, it could be fixed by twiddling the dpi, but it was too troublesome.

当svg单元不是px(例如cm)时,Inkscape似乎就不起作用了。我得到了一个空白的图像。也许,它可以通过玩弄dpi来解决,但它太麻烦了。

Svgexport is a node.js program and so not generally useful.

Svgexport是一个节点。js程序,所以不太有用。

Imagemagick's convert works ok with:

Imagemagick的转换可以使用:

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

If you use -resize, the image is fuzzy and the file is much larger.

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

BEST

请接受我最美好的祝愿,

~$ rsvg  -w 1024 -h 1024 infile.svg  outfile.png

It is fastest, has the fewest dependencies, and the output is about 30% smaller than convert. Install librsvg2-bin to get it. There does not appear to be a man page but you can type:

它是最快的,具有最少的依赖性,并且输出比转换的要小30%左右。安装librsvg2-bin来获取它。似乎没有男人的页面,但你可以打字:

~$ rsvg --help

to get some assistance. Simple is good.

得到一些帮助。简单是好的。

#6


10  

After following the steps in Jose Alban's answer, I was able to get ImageMagick to work just fine using the following command:

按照何塞·阿尔班回答的步骤,我可以使用以下命令让ImageMagick工作得很好:

convert -density 1536 -background none -resize 100x100 input.svg output-100.png

The number 1536 comes from a ballpark estimate of density, see this answer for more information.

数字1536来自密度的估计,更多信息请看这个答案。

#7


8  

In order to rescale the image, the option -density should be used. As far as I know the standard density is 72 and maps the size 1:1. If you want the output png to be as double as big as the original svg set density to 72*2=144

为了重新调整图像的大小,应该使用选项-密度。据我所知,标准密度是72,并映射成1:1。如果您希望输出png的大小是原始svg的两倍,请将密度设置为72*2=144

convert -density 144 source.svg target.png

将密度144源。svg target.png

#8


6  

why don't you give a try to inkscape command line, this is my bat file to convert all svg in this dir to png:

为什么不尝试使用inkscape命令行呢?这是我将这个目录中的svg转换为png的bat文件:

FOR %%x IN (*.svg) DO C:\Ink\App\Inkscape\inkscape.exe %%x -z --export-dpi=500 --export-area-drawing --export-png="%%~nx.png"

为%x IN (*.svg)做C:\Ink\App\Inkscape Inkscape。exe %x -z——export-dpi=500——export-area-draw -export-png="%%~nx.png"

#9


2  

One thing that just bit me was setting the -density AFTER the input file name. That didn't work. Moving it to the first option in convert (before anything else) made it work (for me, YMMV, etc).

有一件事让我很不爽,那就是在输入文件名之后设置-density。没有工作。将它移动到皈依的第一个选项(在其他选项之前)使它工作(对我、YMMV等)。

#10


1  

I came to this post - but I just wanted to do the conversion by batch and quick without the usage of any parameters (due to several files with different sizes).

我来到这篇文章——但是我只是想以批处理和快速的方式进行转换,而不使用任何参数(由于有几个不同大小的文件)。

rsvg drawing.svg drawing.png

For me the requirements were probably a bit easier than for the original author. (Wanted to use SVGs in MS PowerPoint, but it doesn't allow)

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

#11


0  

I've solved this issue through changing the width and height attributes of the <svg> tag to match my intended output size and then converting it using ImageMagick. Works like a charm.

通过更改 标记的宽度和高度属性以匹配预期的输出大小,然后使用ImageMagick对其进行转换,我解决了这个问题。就像一个魅力。

Here's my Python code, a function that will return the JPG file's content:

下面是我的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

#12


0  

For simple SVG to PNG conversion I found cairosvg (https://cairosvg.org/) performs better than ImageMagick. Steps for install and running on all SVG files in your directory.

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

pip3 install cairosvg

Open a python shell in the directory which contains your .svg files and run:

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

import os

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

This will also ensure you don't overwrite your original .svg files, but will keep the same name. You can then move all your .png files to another directory with:

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

$ mv *.png [new directory]

#13


-1  

The top answer by @808sound did not work for me. I wanted to resize 如何将SVG转换成具有图像效果的PNG ?

@808sound给出的最上面的答案对我不起作用。我想调整

and got 如何将SVG转换成具有图像效果的PNG ?

并得到了

So instead I opened up Inkscape, then went to File, Export as PNG fileand a GUI box popped up that allowed me to set the exact dimensions I needed.

所以我打开Inkscape,然后到File中,导出为PNG文件,然后弹出一个GUI框,允许我设置所需的确切尺寸。

Version on Ubuntu 16.04 Linux: Inkscape 0.91 (September 2016)

Ubuntu 16.04 Linux版本:Inkscape 0.91(2016年9月)

(This image is from Kenney.nl's asset packs by the way)

(这张照片来自肯尼。顺便说一下,nl的资产包)