2011-02-04 51 views
6

Đây là mã tôi đang sử dụng:Làm thế nào để duy trì tính minh bạch khi thay đổi kích thước PNG sử dụng Perl và GD

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

Những hình ảnh đầu ra có một nền đen và tất cả các kênh alpha bị mất.

I'am sử dụng hình ảnh này: http://i54.tinypic.com/33ykhad.png

Đây là kết quả: http://i54.tinypic.com/15nuotf.png

Tôi đã thử tất cả các kết hợp của alpha() và độ trong suốt() vv điều, không ai trong số họ làm việc .... .

Xin hãy giúp tôi giải quyết vấn đề này.

+0

thể trùng lặp của [PNG hình ảnh minh bạch có thể được bảo quản khi sử dụng PHP GDlib imagecopyresampled?] (Http://stackoverflow.com/questions/32243/can-png-image-transparency-be -preserved-when-using-phps-gdlib-imagecopyresampled) – daxim

Trả lời

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'); 
Các vấn đề liên quan