[PerlChina] 请教熟悉图像处理的朋友(我的解决方案)

Jester jester at perlchina.org
Tue Aug 16 20:43:59 PDT 2005


上次的问题多谢各位朋友的热心帮忙。
最近我想出了一个只用GD模块的解决方案,和大家共享一下。

附件中的example.png是处理前的图像。
我尝试给GD添加了一个方法,代码如下:
#---------------------------------------
sub GD::Image::JesterPaint{
 my $this=shift;
 @_==5 or croak('Usage: KEGGrender(x1,y1,x2,y2,color)');
 my ($x1,$y1,$x2,$y2,$color)=@_;
 my $old=$this->getPixel($x1,$y1); #这里我取了左上角这点的颜色作为替换的对象,可以根据需要自行修改
 for(my $i=$x1;$i<=$x2;$i++)
 {
  for(my $j=$y1;$j<=$y2;$j++)
  {
  next if($this->getPixel($i,$j) eq $old); #change 'if' to 'unless' if you want to paint foreground instead
  $this->setPixel($i,$j,$color);
  }
 }
}
#---------------------------------------
可以把这段代码放在程序里,也可以直接放在系统安装的GD.pm文件里(如果你希望以后用的话咯!:P)

用法很简单,把你想要涂色的区域的坐标和颜色作为参数即可。主程序如下:
#---------------------------------------
use GD;
open F,$ARGV[0] or die "Usage: $0 <example.png>  >  output.png\n";
my $i=newFromPng GD::Image(*F);
close F;
my $w=$i->colorAllocate(255,255,255);
my $g=$i->colorAllocate(0,255,0);
$i->JesterPaint(12,2,58,19,$g);
binmode STDOUT;
print $i->png;
#---------------------------------------

完整的代码,我也放在附件里面(test.pl)。运行的后得到的效果是output.png。
另外,作为一个附带的收获,我发现它还有另外一个功能――改变前景色(也就是这里的字体颜色)而不是背景色。
方法很简单,把JesterPaint方法代码里面的if替换成unless,然后把主程序里面的颜色改成红色($g=$i->colorAllocate(255,0,0);
)。再试试吧,就能得到附件中output2.png的效果了。算是个意外的收获吧。^_^

因为,我所要处理的区域都很小,所以暂时没有看出运行速度上的问题,因为是遍历,我还是有些担心……
另外,现在处理的都是简单的纯色图像,复杂了,比如有渐进色什么的,肯定就有问题了……:(


+----------------------+
|        Jester        |
|                      |
| jester at perlchina.org |
+----------------------+

----- Original Message ----- 
From: "Jester" <jester at perlchina.org>
To: <china-pm at pm.org>
Sent: Friday, July 29, 2005 2:25 PM
Subject: 请教熟悉图像处理的朋友


> 
> 哪位做过类似我的附件里面的图形中的这样的处理?
> 也就是在一个指定的区域中打上底色,而且要求保留原来的文字。
> 我只会用GD,但是里面没有这样的方法。单是fill肯定不行,因为有些文字有圈的,会fill不上的……
> 不知道有没有哪位知道用什么方法?或者有什么模块可以做的?
-------------- next part --------------
A non-text attachment was scrubbed...
Name: example.png
Type: image/png
Size: 1062 bytes
Desc: not available
Url : http://mail.pm.org/pipermail/china-pm/attachments/20050817/f61dd8a8/example.png
-------------- next part --------------
z'???r?????????z???S????bq?b?????jd????z??????V???m???i????z???_?)?o???g????t??]w??????
-------------- next part --------------
A non-text attachment was scrubbed...
Name: output.png
Type: image/png
Size: 271 bytes
Desc: not available
Url : http://mail.pm.org/pipermail/china-pm/attachments/20050817/f61dd8a8/output.png
-------------- next part --------------
A non-text attachment was scrubbed...
Name: output2.png
Type: image/png
Size: 283 bytes
Desc: not available
Url : http://mail.pm.org/pipermail/china-pm/attachments/20050817/f61dd8a8/output2.png


More information about the China-pm mailing list