Debian Codegraph @

samples/inline_replace_color.pl

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