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

标签 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 channel 都将丢失。

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

这是结果:http://i54.tinypic.com/15nuotf.png

我尝试了 alpha() 和 transparancy() 等的所有组合,但都没有奏效.....

请帮我解决这个问题。

最佳答案

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');

关于perl - 使用 Perl 和 GD 调整 PNG 大小时如何保持透明度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4900766/

相关文章:

PHP/GD - 透明背景

php - 如何在 Heroku 上安装 GD

使用 nginx 和 FastCGI 的 Perl Web 服务 - 无法读取参数

linux - 监视多个目录以创建文件;如果它们不存在,请发送电子邮件

c# - 如何在文件的一部分上使用 DeflateStream?

PHP - 使用 imagecopy 时颜色不正确

perl - 为什么 `exists` 修改我的常量?

perl - 如何使用 MOSS 脚本?

javascript - 传单 map 未加载图 block