Search code examples
perlimagemagickperlmagick

How do I convert a svg to png in Perl's ImageMagick API PerlMagick?


How do I convert a svg image to png, save it to a file, and collect basic information about it?

#!/usr/bin/perl 
use strict;
use warnings;
use Image::Magick;

my $svg = <<'SVG';
<?xml version="1.0" encoding="utf-8" ?>
<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
  <rect fill="white" height="87" rx="10" ry="10" stroke="black" stroke-width="1" width="56" x="0" y="0"/>
</svg>
SVG

my $im = Image::Magick->new();
$im->Read(blob => $svg) or die "Could not read: $!";

$im->Write(filename => 'test.png') or die "Cannot write: $!";
my $width = $im->Get('height') || '(undef)';
my $height = $im->Get('width') || '(undef)';
my $size = $im->Get('filesize') || '(undef)';

print "$height x $width, $size bytes\n";

When I run this, I get:

(undef) x (undef), (undef) bytes

No errors, no test.png, and image dimensions are undefined.

How do I convert an svg image to png in PerlMagick?

As for whether this is a duplicate: Most other questions, blog posts, and tutorials use the command line ImageMagick convert tool. I want to avoid that. I currently call Inkscape for conversion, but the profiler shows these calls as one of the hot spots in my code base. I am dealing with ~320 svg files and it takes ~15 minutes to convert them. I hope with a library I can get better performance cause I don't need to create new processes and write temp files. I am also looking into Inkscape shell.


Solution

  • You must specify a width and height of the SVG image. The following works for me:

    use strict;
    use warnings;
    use Image::Magick;
    
    my $svg = <<'SVG';
    <?xml version="1.0" encoding="utf-8" ?>
    <svg xmlns="http://www.w3.org/2000/svg" width="300" height="200" version="1.1">
      <rect fill="white" height="87" rx="10" ry="10" stroke="black" stroke-width="1" width="56" x="0" y="0"/>
    </svg>
    SVG
    my $im = Image::Magick->new(magick => 'svg');
    my $status;
    $status = $im->BlobToImage($svg) and warn $status;
    $status = $im->Write(filename => 'test.png') and warn $status;
    my $width = $im->Get('height') || '(undef)';
    my $height = $im->Get('width') || '(undef)';
    my $size = $im->Get('filesize') || '(undef)';
    print "$height x $width, $size bytes\n";
    

    Output:

    300 x 200, 1379 bytes