如何將 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) 位元組
no errors、notest.png和 image 尺寸未定義。
如何在 PerlMagick 中將 svg 影像轉換為 png?
至于這是否是重復的:大多數其他問題、博客文章和教程都使用命令列 ImageMagickconvert工具。我想避免這種情況。我目前呼叫 Inkscape 進行轉換,但分析器將這些呼叫顯示為我的代碼庫中的熱點之一。我正在處理約 320 個 svg 檔案,轉換它們需要約 15 分鐘。我希望通過一個庫我可以獲得更好的性能,因為我不需要創建新行程和撰寫臨時檔案。我也在研究Inkscape shell。
uj5u.com熱心網友回復:
您必須指定 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
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/409719.html
標籤:
