Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi I'm trying to convert some jpeg images to grayscale on the fly, and I thought GD could do it, but to me it looked like the closest thing was
$newimage->colorAllocate($red,$green,$blue);
I tried this
my $newimage = new GD::Image($newW,$newH); $newimage->copyResized($srcimage,0,0,0,0,$newW,$newH,$srcW,$srcH); $newimage->colorAllocate(255,255,255); print $newimage->jpeg;
But there is no change in the colors, so I'm guessing that is not what I am looking for. I'm sure there has to be something out there that will do this though... Thanks

Replies are listed 'Best First'.
Re: converting Jpeg to grayscale
by snadra (Scribe) on Jul 22, 2003 at 13:17 UTC
    Hi,
    I could not find a direct hue reduction (grayscale) either. But you can do a merged copy of the image, whith the copy being grayscaled.
    $image->copyMergeGray($sourceImage,$dstX,$dstY, $srcX,$srcY,$width,$height,$percent)
    snadra
Re: converting Jpeg to grayscale
by Joost (Canon) on Jul 22, 2003 at 13:21 UTC
    You can use convert from the Imagemagick package. Like this: convert -colorspace gray input.jpg output.jpg.

    Or use the Image::Magick module if you can get it to compile.

    Joost.

    -- #!/usr/bin/perl -w use strict;$;= ";Jtunsitr pa;ngo;t1h\$e;r. )p.e(r;ls ;h;a;c.k^e;rs ";$_=$;;do{$..=chop}while(chop);$_=$;;eval$.;
      Or faster, smaller and better at keeping metadata together than ImageMagick: IJG's jpegtran. This has the advantage of preserving the luminance channel exactly, whereas IM is likely to decompress, greyscale, then recompress the image.

      --
      bowling trophy thieves, die!

Re: converting Jpeg to grayscale
by snadra (Scribe) on Jul 22, 2003 at 13:33 UTC
    If you are willing to use other modules instead of GD you could also use Imager. It is easier to install than Image::Magick, and it is capable to do many image manipulation stuff as well.
    It also has gif support, if you need that. It will ask if gif support should be enabled during the installation.
    For setting the hue and saturation of the image do this:
    my $color = Imager::Color->new(hue=>120, value=>1, saturation=>0.5);
      Maybe I'm just to dumb to understand the documentation, but this seems like it should work no?
      use Imager; my $pregray = Imager->new(); $pregray->copy($original); my $grey = $pregray->convert(preset=>'grey');
      Or am I passing in the original image wrong?
Re: converting Jpeg to grayscale
by zentara (Cardinal) on Jul 22, 2003 at 15:06 UTC
    This works for me:
    #!/usr/bin/perl use warnings; use strict; use Imager; my $file = shift; my $img = Imager->new(); $img->open(file=>$file) or die $img->errstr(); my $newimg = $img->convert(preset=>'grey'); $newimg->write(file=>'gray.jpg');