2
votes

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.

2
Did my answer sort out your problem? If so, please consider accepting it as your answer - by clicking the hollow tick/checkmark beside the vote count. If not, please say what didn't work so that I, or someone else, can assist you further. Thanks. meta.stackexchange.com/questions/5234/… - Mark Setchell

2 Answers

3
votes

I am not familiar with Perl's Imager module, but I looked through the documentation and can't find anything related to setting the background colour which is what happens in other packages (e.g. gd, ImageMagick) to transparent pixels when you turn off the alpha mask.

Forgive me if this is miles more vague than any of my other answers, but it may get you started. I think you may need to do the following:

  • create a new, white image (without alpha) the same size as your PNG
  • composite your image over the new, white background

I suspect the second step above will look something like:

$white = $white->compose(src=>$img)

You may also need to add mask=>$img to the arguments, and you may also need to experiment with opacity=>0.5 or 1.0 or 0.0.

If anyone knows better, just tell me and I will delete this answer!

2
votes

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.