【问题标题】:How do I convert a svg to png in Perl's ImageMagick API PerlMagick?如何在 Perl 的 ImageMagick API PerlMagick 中将 svg 转换为 png?
【发布时间】:2022-01-08 23:22:15
【问题描述】:

如何将 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";

当我运行它时,我得到:

(undef) x (undef), (undef) 字节

没有错误,没有test.png,并且图像尺寸未定义。

如何在 PerlMagick 中将 svg 图像转换为 png?

至于这是否重复:其他大多数问题、博客文章和教程都使用命令行 ImageMagick convert 工具。我想避免这种情况。我目前调用 Inkscape 进行转换,但分析器将这些调用显示为我的代码库中的热点之一。我正在处理约 320 个 svg 文件,转换它们需要约 15 分钟。我希望通过一个库我可以获得更好的性能,因为我不需要创建新进程和编写临时文件。我也在调查Inkscape shell

【问题讨论】:

  • 这能回答你的问题吗? How to convert a SVG to a PNG with ImageMagick?
  • 您是否在网络上搜索过 imagemagick svg to png?很多点击。
  • @JimGarrison 是的,我看到了您链接的问题,但想避免调用外部程序。我已经编辑了问题以澄清。
  • 如果我将您的内联 svg 图像保存到文件 sample.svg 并运行命令 display sample.svg 我得到错误 "display-im6.q16: must specify image size" 我认为您的内联 svg 缺少 widthheight 参数?

标签: perl imagemagick perlmagick


【解决方案1】:

您必须指定 SVG 图像的宽度和高度。以下对我有用:

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";

输出

300 x 200, 1379 bytes

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-08
    • 1970-01-01
    • 2015-07-11
    • 2012-11-30
    • 1970-01-01
    • 2014-01-05
    • 2018-10-26
    • 1970-01-01
    相关资源
    最近更新 更多