- added sample files missing from MANIFEST
[imager.git] / samples / inline_replace_color.pl
1 #!perl -w
2 use strict;
3 use Imager;
4
5 =head1 NAME
6
7 inline_replace_color - replace one color with another in an image, using Inline
8
9 =head1 SYNOPSIS
10
11   perl inline_replace_color fromcolor tocolor inimage outimage
12
13 =head1 DESCRIPTION
14
15 This is a simple demonstration of using Imager with Inline::C to
16 replace one color in an image with another.
17
18 Most of the work is done in the inline_replace_color() function.
19
20 =over
21
22 =cut
23
24 # extract parameters
25 my $from = shift;
26
27 my $to = shift;
28
29 my $in = shift;
30
31 my $out = shift
32   or die "Usage: $0 fromcolor tocolor inimage outimage\n";
33
34 # convert the colors into objects
35 my $from_color = Imager::Color->new($from)
36   or die "Cannot convert fromcolor $from into a color: ", Imager->errstr, "\n";
37
38 my $to_color = Imager::Color->new($to)
39   or die "Cannot convert tocolor $to into a color: ", Imager->errstr, "\n";
40
41 # do the work
42 my $img = Imager->new;
43 $img->read(file=>$in)
44   or die "Cannot read image $in: ", $img->errstr, "\n";
45
46 # unlike the transform2() version this works in place
47 inline_replace_color($img, $from_color, $to_color);
48
49 $img->write(file=>$out)
50   or die "Cannot write image $out: ", $img->errstr, "\n";
51
52 =item inline_replace_color
53
54 Called:
55
56   inline_replace_color($in_image, $from_color, $to_color);
57
58 Returns a new image object with colors replaced.
59
60 =cut
61
62 use Inline C => <<'EOS' => WITH => 'Imager';
63 void
64 inline_replace_color(Imager::ImgRaw img, Imager::Color from, Imager::Color to) {
65   int x, y, ch;
66   i_color c;
67
68   for (x = 0; x < img->xsize; ++x) {
69     for (y = 0; y < img->ysize; ++y) {
70       int match = 1;
71       i_gpix(img, x, y, &c);
72       for (ch = 0; ch < img->channels; ++ch) {
73         if (c.channel[ch] != from->channel[ch]) {
74           match = 0;
75           break;
76         }
77       }
78       if (match)
79         i_ppix(img, x, y, to);
80     }
81   }
82 }
83 EOS
84
85 __END__
86
87 =back
88
89 =head1 REVISION
90
91 $Revision: 816 $
92
93 =head1 AUTHOR
94
95 Tony Cook <tony@develop-help.com>
96
97 =head1 SEE ALSO
98
99 Imager, Imager::Inline, Imager::API, Imager::Color, Imager::Files
100
101 =cut