Search code examples
perlimage-processingpngjpegalpha-transparency

Perl Imager: how do I make the alpha channel become black insead of white?


I wrote this code to convert a PNG image to JPEG:

use Imager;
use strict;

my $img = Imager->new( file => './fsc.png' );
$img = $img->convert( preset => 'noalpha' );
$img = $img->scale( xpixels => 100 );
$img->write( type => 'jpeg', file => './fsc.jpg' );

When passing a PNG with alpha channel (transparent), the background becomes black. What I would like to do is to have it white, instead.

Curiously, if I just write:

my $img = Imager->new( file => './fsc.png' );
$img->write( type => 'jpeg', file => './fsc.jpg' );

the jpeg has white background, but of course it's not scaled to the size I need.


Solution

  • After a suggestion by the author of Imager, it seems that the most straightforward solutions is this:

    use Imager;
    
    my $img = Imager->new( file => './fsc.png' );
    $img = $img->scale( xpixels => 100 );
    $img->write( type => 'jpeg', file => './fsc.jpg', i_background => Imager::Color->new("#FFF") );
    

    That is, the i_background parameter to save does the trick.