#!/usr/bin/perl
##################
#
# Extract the red channel from a jpeg image 
# and export an image with only that color.
#
##################
use strict;
use warnings;
use GD;

my $input     = "tim.jpeg";
my $truecolor = 1;             # Yes; use 24-bits per pixel.
print "Reading in jpeg file '$input'... with 24 bits per pixel";
my $img    = GD::Image->newFromJpeg($input, $truecolor);
print "done.\n";

my ($width, $height) = $img->getBounds();
print " '$input' is $width x $height.\n";

my $newImage = GD::Image->new($width,$height,$truecolor);
my $black = $newImage->colorAllocate(0,0,0);
my $white = $newImage->colorAllocate(255,255,255);

#my (@red, @green, @blue);
#for my $w (0..$width-1){
#  for my $h (0..$height-1){
#    ($red[$w][$h], $green[$w][$h] = 0, $blue[$w][$h]) = 
#      $img->rgb( $img->getPixel($w,$h) );
#  }
#}

my ($red, $green, $blue);
for my $w (0..$width-1){
  for my $h (0..$height-1){
    ($red, $green, $blue) = $img->rgb( $img->getPixel($w,$h) );
    my $color = $newImage->colorAllocate($red,0,0);
    $newImage->setPixel($w,$h,$color);
  }
}

my $output = "tim_red.jpeg";
unlink $output;
print "Writing '$output'... ";
open    OUT, ">$output" or die "Oops couldn't create '$output'";
binmode OUT;
print   OUT $newImage->jpeg;
close   OUT;
print "done.\n";
