[英]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?如何将 svg 图像转换为 png、将其保存到文件并收集有关它的基本信息?
#!/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
(undef) x (undef), (undef) 字节
No errors, no test.png
, and image dimensions are undefined.没有错误,没有
test.png
,并且图像尺寸未定义。
How do I convert an svg image to png in PerlMagick?如何在 PerlMagick 中将 svg 图像转换为 png?
As for whether this is a duplicate: Most other questions, blog posts, and tutorials use the command line ImageMagick convert
tool.至于这是否是重复的:其他大多数问题、博文和教程都使用命令行 ImageMagick
convert
工具。 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.
我目前调用 Inkscape 进行转换,但分析器将这些调用显示为我的代码库中的热点之一。 I am dealing with ~320 svg files and it takes ~15 minutes to convert them.
我正在处理约 320 个 svg 文件,转换它们需要约 15 分钟。 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 .
我也在研究Inkscape shell 。
You must specify a width and height of the SVG image.您必须指定 SVG 图像的宽度和高度。 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 : Output :
300 x 200, 1379 bytes
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.