使用Perl和GD调整PNG大小时如何保持透明度

时间:2011-02-04 17:08:16

标签: perl png gd alpha

这是我正在使用的代码:

!/usr/bin/perl
use GD;
sub resize
{
    my ($inputfile, $width, $height, $outputfile) = @_;
    my $gdo = GD::Image->new($inputfile);

    ## Begin resize

    my $k_h = $height / $gdo->height;
    my $k_w = $width / $gdo->width;
    my $k = ($k_h < $k_w ? $k_h : $k_w);
    $height = int($gdo->height * $k);
    $width  = int($gdo->width * $k);

    ## The tricky part

    my $image = GD::Image->new($width, $height, $gdo->trueColor);
    $image->transparent( $gdo->transparent() );
    $image->copyResampled($gdo, 0, 0, 0, 0, $width, $height, $gdo->width, $gdo->height);

    ## End resize

    open(FH, ">".$outputfile);      
    binmode(FH);
    print FH $image->png();
    close(FH);
}
resize("test.png", 300, 300, "tested.png");

输出图像背景为黑色,所有Alpha通道都丢失。

我正在使用此图片:http://i54.tinypic.com/33ykhad.png

结果如下:http://i54.tinypic.com/15nuotf.png

我尝试了所有alpha()和transparancy()等组合的东西,没有一个工作.....

请帮我解决这个问题。

1 个答案:

答案 0 :(得分:7)

Can PNG image transparency be preserved when using PHP's GDlib imagecopyresampled?

#!/usr/bin/env perl
use strictures;
use autodie qw(:all);
use GD;

sub resize {
    my ($inputfile, $width, $height, $outputfile) = @_;
    GD::Image->trueColor(1);
    my $gdo = GD::Image->new($inputfile);

    {
        my $k_h = $height / $gdo->height;
        my $k_w = $width / $gdo->width;
        my $k   = ($k_h < $k_w ? $k_h : $k_w);
        $height = int($gdo->height * $k);
        $width  = int($gdo->width * $k);
    }

    my $image = GD::Image->new($width, $height);
    $image->alphaBlending(0);
    $image->saveAlpha(1);
    $image->copyResampled($gdo, 0, 0, 0, 0, $width, $height, $gdo->width, $gdo->height);

    open my $FH, '>', $outputfile;
    binmode $FH;
    print {$FH} $image->png;
    close $FH;
}
resize('test.png', 300, 300, 'tested.png');