Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to preserve transparency when resizing PNG using Perl and GD

Tags:

png

perl

alpha

gd

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

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

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

This is the result: http://i54.tinypic.com/15nuotf.png

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

Pleas help me with this issue.

like image 645
Don Avatar asked Feb 04 '11 17:02

Don


1 Answers

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');
like image 167
daxim Avatar answered Oct 13 '22 03:10

daxim