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

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

本文介绍了使用Perl和GD调整PNG大小时如何保持透明度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我正在使用的代码:

This is the code i'm using:

!/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通道均丢失.

The output image has a black background and all alpha channels are lost.

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

I'am using this image: http://i54.tinypic.com/33ykhad.png

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

我尝试了alpha()和transparancy()等的所有组合,但都不起作用.....

I tried all combinations of alpha() and transparancy() etc. things, none of them worked.....

请帮助我解决这个问题.

Pleas help me with this issue.

推荐答案

#!/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和GD调整PNG大小时如何保持透明度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 04:41