想要在已存在的 SVG 基础上做图,所以需要添加函数 newFromSVG()
。
这里采用模块 SVG::Parser
来将 SVG 文件中内容读进来,成为一个 svg 对象。
示例代码:
#!/usr/bin/perl
# by lhtk : lhtk80t7@gmail.com
#
use strict;
use warnings;
use GD::SVG;
use SVG::Parser;
use autodie qw/open close/;
# input, output
my $svg_i = 'input.svg';
my $svg_o = 'tmp.svg';
my $im = GD::SVG::Image->newFromSVG(2000,2000,$svg_i); # 直接从 SVG 文件来构建
# =========================================
# 一些什么乱七八糟的代码…………
# =========================================
# 输出
my $fh_svg_o;
open $fh_svg_o, '>', $svg_o;
#print SVGO $svg->xmlify;
print $fh_svg_o $im->svg();
close $fh_svg_o;
# =========================================
# subroutines
# =========================================
package GD::SVG::Image;
# 对 GD::SVG::Image::new 进行修改得到
# 简单改了下
sub newFromSVG {
my ($self,$width,$height,$svg_i,$debug) = @_;
my $this = bless {},$self;
# load SVG in
open my $fh, '<', $svg_i;
my $xml;
{
local $/ = undef;
$xml = <$fh>;
}
close $fh;
my $parser = new SVG::Parser(-debug => 0);
my $img = $parser->parse($xml);
$this->{img} = [$img];
$this->{width} = $width;
$this->{height} = $height;
# Let's create an internal representation of the image in GD
# so that I can easily use some of GD's methods
###GD###$this->{gd} = GD::Image->new($width,$height);
# Let's just assume that we always want the foreground color to be
# black This, for the most part, works for Bio::Graphics. This
# certainly needs to be fixed...
$this->{foreground} = $this->colorAllocate(0,0,0);
$this->{debug} = ($debug) ? $debug : GD::SVG::DEBUG;
return $this;
}
测试了一下,可以成功执行。