簡體   English   中英

如何在 Perl 的 ImageMagick API PerlMagick 中將 svg 轉換為 png?

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

如何將 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

您必須指定 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";

Output

300 x 200, 1379 bytes

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM