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