Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert SVG to PNG while keeping aspect ratio but changing extents?

I'm trying to convert an SVG to a PNG. The SVG is a non-square rectangle. I want the aspect ratio of the image to stay the same, so the extents of the image need to be filled (transparent).

I am on OS X Mavericks, 10.9.2.

I've tried this with 3 tools, and each has issues:

With ImageMagick:

convert -background none -resize 200x200 -gravity center -extent 200x200 rect.svg rect-imagemagick.png 

START --

enter image description here

END --

Image is square with correct aspect ratio, but is fuzzy. I've seen other users report this issue with imagemagick converting SVGs to PNG. I have upgraded imagemagick to use rsvg (via brew) as can be seen in the delegates of the version below.

Version:

# convert --version
Version: ImageMagick 6.9.1-3 Q16 x86_64 2016-01-23 http://www.imagemagick.org
Copyright: Copyright (C) 1999-2015 ImageMagick Studio LLC
License: http://www.imagemagick.org/script/license.php
Features: DPC Modules
Delegates (built-in): bzlib cairo fontconfig freetype jng jpeg ltdl lzma png rsvg tiff xml zlib

With rsvg:

rsvg-convert -a -w 200 -h 200 rect.svg > rect-rsvg.png

START --

enter image description here

END --

Image is clear with correct aspect ratio, but I don't see a way to make it square (extend the image).

Version:

# rsvg-convert --version
rsvg-convert version 2.40.9

With Inkscape:

inkscape -z -e rect-inkscape.png -w 200 -h 200 rect.svg

START --

enter image description here

END --

Image is square and clear, but with incorrect aspect ratio.

Version:

# inkscape --version
W: AppleCollationOrder setting not found, using AppleLocale.
Setting LANGSTR from AppleLocale: en
Overriding empty LANG from /usr/share/locale/locale.alias
Setting Language: en_US.UTF-8
Inkscape 0.48.5 r10040 (Jul 12 2014)
like image 371
Brian Avatar asked Jan 25 '16 17:01

Brian


1 Answers

Okay, I realized this has a simple answer if I combine two of the utilities:

rsvg-convert -a -w 200 -h 200 rect.svg > rect-rsvg.png
convert -background none -resize 200x200 -gravity center -extent 200x200 rect-rsvg.png rect-correct.png

First convert to PNG with rsvg-convert, which correctly converts but does not extend. And then extend with imagemagick from PNG to PNG.

like image 132
Brian Avatar answered Nov 15 '22 09:11

Brian