7 replace_color - replace one color with another in an image
11 perl replace_color fromcolor tocolor inimage outimage
15 This is a simple demonstration of Imager::transform2 that replaces one
16 color with another in an image.
18 Note: this works with full color images, and always produces a 3
19 channel output image - the alpha channel (if any) is not preserved.
21 Most of the work is done in the replace_color() function.
35 or die "Usage: $0 fromcolor tocolor inimage outimage\n";
37 # convert the colors into objects
38 my $from_color = Imager::Color->new($from)
39 or die "Cannot convert fromcolor $from into a color: ", Imager->errstr, "\n";
41 my $to_color = Imager::Color->new($to)
42 or die "Cannot convert tocolor $to into a color: ", Imager->errstr, "\n";
45 my $img = Imager->new;
47 or die "Cannot read image $in: ", $img->errstr, "\n";
49 my $result = replace_color($img, $from_color, $to_color)
50 or die "Cannot replace colors: ", Imager->errstr, "\n";
52 $result->write(file=>$out)
53 or die "Cannot write image $out: ", $result->errstr, "\n";
59 my $result = replace_color($in_image, $from_color, $to_color);
61 Returns a new image object with colors replaced.
66 my ($img, $from_color, $to_color) = @_;
68 my ($from_red, $from_green, $from_blue) = $from_color->rgba;
69 my ($to_red, $to_green, $to_blue) = $to_color->rgba;
70 my $rpnexpr = <<'EOS';
73 # check against the from_color
75 @pix green from_green eq
76 @pix blue from_blue eq
79 to_red to_green to_blue rgb @pix ifp
81 # rpnexpr doesn't really support comments - remove them
82 $rpnexpr =~ s/^#.*\n//mg;
85 from_red => $from_red,
86 from_green => $from_green,
87 from_blue => $from_blue,
89 to_green => $to_green,
92 return Imager::transform2({ rpnexpr => $rpnexpr,
93 constants => \%constants },
107 Tony Cook <tony@develop-help.com>
111 Imager, Imager::Engines, Imager::Color, Imager::Files