Converting SVG to PNG

This article will show you how to convert SVG to PNG using RMagick


Published on:October 18, 2015

Introduction

Sometimes you may need to convert SVG files to PNG. For example, many charging libraries offer the ability to output as SVG, but they may not allow you to export as a PNG. Fortunately you can easily do this using RMagick. RMagick is a gem that allows you to access ImageMagick. ImageMagick is a software package that allows you to manipulate images. Because of this, we will first need to install ImageMagick. That can be accomplished using the commands below.

OS-X (Homebrew):

brew install imagemagick
Debian Based Systems:

sudo apt-get install imagemagick
Red Hat Based Systems:

sudo yum install imagemagick

For other systems, you'll need to consult the ImageMagick website.

After you install ImageMagick, you'll need to install the rmagick gem. Simply run the command below to install it.

Terminal Commands:

gem install rmagick

Converting the SVG

Now it's a simple matter of converting the file. Below is sample code to do exactly that.


require 'rmagick'
include Magick

svg = %{
  <svg xmlns="http://www.w3.org/2000/svg"  width="120" height="120" viewPort="0 0 120 120" version="1.1">
          <rect width="100" height="100" fill="rgb(255, 255, 0)" stroke-width="1" stroke="rgb(0, 0, 0)" />
       </svg>
}

img, data = Magick::Image.from_blob(svg) {
  self.format = 'SVG'
  self.background_color = 'transparent'
}

img.write 'my_svg.png'

How does it work? First we include the RMagick library. Next, we set a variable to the contents of the SVG. Note that this could just as easily be loaded from a file or submitted by the end user. Finally, we use RMagick to convert the file to an SVG.

That's it! Thanks for reading!