blib/lib/Image/Base/Magick.pm

filter: Statementstmt 85.7% 12 / 14 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 5 / 5 Podpod n/a totaltotal 89.4% 17 / 19 CC 1 SCAR 0.6
CC
1
Cov
86%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.1
↑ Summary
1 # Copyright 2010, 2011, 2012, 2017, 2021 Kevin Ryde
2  
3 # This file is part of Image-Base-Magick.
4 #
5 # Image-Base-Magick is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by the
7 # Free Software Foundation; either version 3, or (at your option) any later
8 # version.
9 #
10 # Image-Base-Magick is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
12 # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13 # for more details.
14 #
15 # You should have received a copy of the GNU General Public License along
16 # with Image-Base-Magick. If not, see <http://www.gnu.org/licenses/>.
17  
18  
19 # file:///usr/share/doc/imagemagick-6-common/html/www/perl-magick.html
20 # file:///usr/share/doc/imagemagick-6-common/html/www/formats.html
21  
22 package Image::Base::Magick;
23 2 ▶use 5.004;
Subroutine BEGIN: called CC=1 SCAR=0.0
24 2 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
25 2 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
26 2 ▶use Fcntl;
Subroutine BEGIN: called CC=1 SCAR=0.0
27 0 ▶use Image::Magick;
Subroutine BEGIN: called CC=1 SCAR=2.6
28 use vars '$VERSION', '@ISA';
29  
30 use Image::Base;
31 @ISA = ('Image::Base');
32  
33 $VERSION = 7;
34  
35 # uncomment this to run the ### lines
36 # use Smart::Comments '###';
37  
38  
39 sub new {
40 my ($class, %params) = @_;
41 ### Image-Base-Magick new(): %params
42 my $err;
43  
44 # $obj->new(...) means make a copy, with some extra settings
45 if (ref $class) {
46 my $self = $class;
47 $class = ref $self;
48 if (! defined $params{'-imagemagick'}) {
49 $params{'-imagemagick'} = $self->get('-imagemagick')->Clone;
50 }
51 # inherit everything else
52 %params = (%$self, %params);
53 ### copy params: \%params
54 }
55  
56 if (! defined $params{'-imagemagick'}) {
57 # Crib note: passing attributes to new() is the same as a subsequent
58 # set() except no error return from new()
59 my $m = $params{'-imagemagick'} = Image::Magick->new;
60  
61 # must apply -width, -height as "size" before ReadImage()
62 if (exists $params{'-width'} || exists $params{'-height'}) {
63 my $width = delete $params{'-width'} || 0;
64 my $height = delete $params{'-height'} || 0;
65 ### Set(size) -width,-height: "${width}x${height}"
66 if ($err = $m->Set (size => "${width}x${height}")) {
67 croak $err;
68 }
69 }
70 ### ReadImage xc-black ...
71 if ($err = $m->ReadImage('xc:black')) {
72 croak $err;
73 }
74 }
75 my $self = bless {}, $class;
76 $self->set (%params);
77  
78 if (defined $params{'-file'}) {
79 $self->load;
80 }
81  
82 ### new made: $self
83 return $self;
84 }
85  
86 # "size" is the size of the canvas
87 # "width" and "height" are the size of a ReadImage() file, or something
88 # file:///usr/share/doc/imagemagick/www/perl-magick.html#get-attribute
89 #
90 sub _magic_get_width {
91 my ($m, $idx) = @_;
92 my $size;
93 if (defined ($size = $m->Get('size'))) {
94 # ### $size
95 # ### split: [ split /x/, $size ]
96 # ### return: (split /x/, $size)[$idx||0]
97 return (split /x/, $size)[$idx||0];
98 } else {
99 return 0;
100 }
101 }
102 sub _magic_get_height {
103 my ($m) = @_;
104 _magic_get_width ($m, 1);
105 }
106 my %attr_to_get_func = (-width => \&_magic_get_width,
107 -height => \&_magic_get_height,
108 );
109 my %attr_to_GetSet = (-file => 'filename',
110 # these not documented yet ...
111 -ncolours => 'colors',
112 -file_format => 'magick',
113 );
114 sub _get {
115 my ($self, $key) = @_;
116 ### Image-Base-Magick _get(): $key
117  
118 my $m = $self->{'-imagemagick'};
119 if (my $func = $attr_to_get_func{$key}) {
120 return &$func($m);
121 }
122 if (my $attribute = $attr_to_GetSet{$key}) {
123 ### Get: $attribute
124 ### is: $m->Get($attribute)
125 return $m->Get($attribute);
126 }
127 return $self->SUPER::_get ($key);
128 }
129  
130 sub set {
131 my ($self, %params) = @_;
132 ### Image-Base-Magick set(): \%params
133  
134 foreach my $key ('-ncolours') {
135 if (exists $params{$key}) {
136 croak "Attribute $key is read-only";
137 }
138 }
139  
140 # apply this first
141 if (my $m = delete $params{'-imagemagick'}) {
142 $self->{'-imagemagick'} = $m;
143 }
144  
145 my $m = $self->{'-imagemagick'};
146 my @set;
147  
148 if (exists $params{'-width'} || exists $params{'-height'}) {
149 # FIXME: might prefer a crop on shrink, and some sort of extend-only on
150 # grow
151  
152 my @resize;
153 my $width = delete $params{'-width'};
154 if (defined $width && $width != _magic_get_width($m)) {
155 push @resize, width => $width;
156 }
157 my $height = delete $params{'-height'};
158 if (defined $height && $height != _magic_get_height($m)) {
159 push @resize, height => $height;
160 }
161 # my $width = delete $params{'-width'};
162 # my $height = delete $params{'-height'};
163 if (! defined $width) { $width = _magic_get_width($m); }
164 if (! defined $height) { $height = _magic_get_height($m); }
165 # $m->Resize (width => $width, height => $height);
166  
167 if (@resize) {
168 ### Resize
169 $m->Resize (@resize);
170 }
171 ### Set(size): "${width}x${height}"
172 push @set, size => "${width}x${height}";
173 }
174  
175 foreach my $key (keys %params) {
176 my $attribute;
177 if ($attribute = $attr_to_GetSet{$key}) {
178 push @set, $attribute, delete $params{$key};
179 }
180 }
181 if (@set) {
182 ### Set(): @set
183 if (my $err = $m->Set(@set)) {
184 croak $err;
185 }
186 }
187  
188 ### store params: %params
189 %$self = (%$self, %params);
190 }
191  
192 sub load {
193 my ($self, $filename) = @_;
194 ### Image-Base-Magick load()
195 if (@_ > 1) {
196 $self->set('-file', $filename);
197 } else {
198 $filename = $self->get('-file');
199 }
200 ### load filename: $filename
201 ### into m: $self->{'-imagemagick'}
202  
203  
204 # This nonsense seems to be necessary to read from a filehandle to avoid
205 # "%d" interpretation on a named file.
206 #
207 # Must temporary $m->Set(filename=>'') or else Read() seems to prefer the
208 # filename attribute over the Read(file=>), or something.
209 #
210 # sysopen() is used to avoid perl two-arg open() whitespace stripping etc.
211 #
212 # @$m=() clear out existing image, as the Read() adds to the canvas.
213 #
214  
215 sysopen FH, $filename, Fcntl::O_RDONLY()
216 or croak "Cannot open $filename: $!";
217 binmode FH
218 or croak "Cannot set binmode for $filename: $!";
219  
220 my $m = $self->{'-imagemagick'};
221 if (my $err = $m->Set(filename => '')) {
222 close FH;
223 croak 'Oops, cannot temporarily unset filename attribute: ',$err;
224 }
225  
226 my @old_ims = @$m;
227 @$m = ();
228  
229 ### empty before load: $m
230 ### file size: -s \*FH
231 ### width: $m->Get('width')
232 ### height: $m->Get('height')
233 ### size: $m->Get('size')
234 ### filename: $m->Get('filename')
235  
236 my $readerr = $m->Read (file => \*FH);
237  
238 ### load leaves magick: $m
239 ### array: [@$m]
240 ### width: $m->Get('width')
241 ### height: $m->Get('height')
242 ### size: $m->Get('size')
243  
244 if (my $err = $m->Set(filename => $filename)) {
245 close FH;
246 @$m = @old_ims;
247 croak 'Oops, cannot restore filename attribute: ',$err;
248 }
249  
250 if (! close FH) {
251 @$m = @old_ims;
252 return "Error closing $filename: $!";
253 }
254  
255 if ($readerr) {
256 @$m = @old_ims;
257 croak $readerr;
258 }
259  
260 if (! scalar(@$m)) {
261 @$m = @old_ims;
262 croak 'ImageMagick Read didn\'t read an image';
263 }
264  
265 # canvas size as size of image loaded
266 my ($width, $height);
267 if (! defined ($width = $m->Get('width'))
268 || ! defined ($height = $m->Get('height'))) {
269 @$m = @old_ims;
270 croak 'ImageMagick Read didn\'t give width,height';
271 }
272 my $size = "${width}x${height}";
273 if (my $err = $m->Set (size => $size)) {
274 @$m = @old_ims;
275 croak "Cannot set size $size: $err";
276 }
277 }
278  
279  
280 # my $m = $self->{'-imagemagick'};
281 # my @old_ims = @$m;
282 # @$m = ();
283 # if (my $err = $m->Read ($filename)) {
284 # @$m = @old_ims;
285 # croak $err;
286 # }
287  
288  
289 # not documented ... probably doesn't work
290 sub load_fh {
291 my ($self, $fh) = @_;
292 ### Image-Base-Magick load_fh()
293 my $err;
294 if ($err = $self->{'-imagemagick'}->Read (file => $fh)) {
295 croak $err;
296 }
297 }
298  
299 # not yet documented ... and untested
300 sub load_string {
301 my ($self, $str) = @_;
302 my $err;
303 if ($err = $self->{'-imagemagick'}->Read (blob => $str)) {
304 croak $err;
305 }
306 }
307  
308 sub save {
309 my ($self, $filename) = @_;
310 ### Image-Base-Magick save(): @_
311 if (@_ > 1) {
312 $self->set('-file', $filename);
313 } else {
314 $filename = $self->get('-file');
315 }
316 ### $filename
317 ### _save_options: _save_options($self)
318  
319  
320 # Not using Write(filename=>) because it expands "%d" to a sequence
321 # number, per file:///usr/share/doc/imagemagick/www/perl-magick.html#read
322 #
323 # Use sysopen() so as not to interpret whitespace etc on $filename.
324 #
325 sysopen (FH, $filename,
326 Fcntl::O_WRONLY() | Fcntl::O_TRUNC() | Fcntl::O_CREAT())
327 or croak "Cannot create $filename: $!";
328 binmode FH
329 or croak "Cannot set binmode on $filename: $!";
330 if (my $err = $self->{'-imagemagick'}->Write (file => \*FH,
331 _save_options($self))) {
332 close FH;
333 croak $err;
334 }
335 close FH
336 or croak "Error closing $filename: $!";
337  
338 $self->set('-file', $filename);
339 }
340  
341 # if (my $err = $self->{'-imagemagick'}->Write (filename => $filename,
342 # _save_options($self))) {
343 # croak $err;
344 # }
345  
346  
347 # not yet documented ... might not work
348 sub save_fh {
349 my ($self, $fh) = @_;
350 if (my $err = $self->{'-imagemagick'}->Write (file => $fh,
351 _save_options($self))) {
352 croak $err;
353 }
354 }
355  
356 sub _save_options {
357 my ($self) = @_;
358  
359 # For PNG "quality" option is zlib_compression*10. Or for undef or -1
360 # compressionomit the quality parameter. Docs
361 # file:///usr/share/doc/imagemagick/www/command-line-options.html#quality
362 # Code coders/png.c WriteOnePNGImage() doing png_set_compression_level()
363 # of quality/10 with maximum 9
364 #
365 my $m = $self->{'-imagemagick'};
366 my $format = $m->Get('magick');
367 if ($format eq 'png') {
368 my $zlib_compression = $self->{'-zlib_compression'};
369 if (defined $zlib_compression && $zlib_compression >= 0) {
370 return (quality => $zlib_compression * 10);
371 }
372 }
373  
374 # For JPEG and MIFF "quality" option is a percentage 0 to 100
375 # file:///usr/share/doc/imagemagick-6-common/html/www/perl-magick.html#set-attribute
376 if (defined(my $quality = $self->{'-quality_percent'})) {
377 return (quality => $quality);
378 }
379 return;
380 }
381  
382 # Circa ImageMagick 6.7.7.10 "pixel[]" such as
383 #
384 # $err = $m->set ("pixel[$x,$y]", $colour);
385 #
386 # when setting a negative X,Y or big positive X,Y gets strangely expressed $err
387 #
388 # Exception 445: pixels are not authentic `black' @ error/cache.c/QueueAuthenticPixelCacheNexus/4387 at t/MyTestImageBase.pm line 326
389 #
390 # Using primitive=>'point' avoids that.
391  
392 sub xy {
393 my ($self, $x, $y, $colour) = @_;
394 ### Image-Base-Magick xy(): $x,$y,$colour
395 my $m = $self->{'-imagemagick'};
396 my $err;
397 if (@_ == 4) {
398 # Draw() primitive point avoids error on negative or large x,y
399 $err = $m->Draw (primitive => 'point',
400 fill => $colour,
401 points => "$x,$y");
402  
403 # Or SetPixel() but it takes arrayref color=>[$r,$g,$b], not string
404 # $err = $m->SetPixel (x=>$x, y=>$y, color=>$colour);
405  
406 } else {
407 # cf $m->get("pixel[123,456]") gives a string "$r,$g,$g,$a"
408  
409 # GetPixel() gives list ($r,$g,$b) each in range 0 to 1
410 # and now also alpha transparency it seems
411 my @rgb = $m->GetPixel (x => $x, y => $y);
412 ### @rgb
413 if (@rgb == 1) {
414 $err = $rgb[0];
415 } else {
416 return sprintf '#%02X%02X%02X', map {$_*255} @rgb[0..2];
417 }
418 }
419 if ($err) {
420 croak $err;
421 }
422 }
423  
424 sub line {
425 my ($self, $x1, $y1, $x2, $y2, $colour) = @_;
426 ### Image-Base-Magick line: @_
427 if ($x1==$x2 && $y1==$y2) {
428 # line which is a single point seems to draw nothing, dispatch to xy()
429 $self->xy($x1,$y1,$colour);
430  
431 } elsif (my $err = $self->{'-imagemagick'}
432 ->Draw (primitive => 'line',
433 strokewidth => 1,
434 stroke => $colour,
435 points => "$x1,$y1 $x2,$y2")) {
436 croak $err;
437 }
438 }
439  
440 sub rectangle {
441 my ($self, $x1, $y1, $x2, $y2, $colour, $fill) = @_;
442 ### Image-Base-Magick rectangle: @_
443  
444 # some versions of ImageMagick seemed to draw nothing for a single point,
445 # so dispatch to line() for anything line-like
446 if ($x1==$x2 || $y1==$y2) {
447 $self->line($x1,$y1, $x2,$y2, $colour);
448 } elsif (my $err = $self->{'-imagemagick'}
449 ->Draw (primitive => 'rectangle',
450 ($fill ? 'fill' : 'stroke'), $colour,
451 points => "$x1,$y1 $x2,$y2")) {
452 croak $err;
453 }
454 }
455  
456 sub ellipse {
457 my ($self, $x1, $y1, $x2, $y2, $colour, $fill) = @_;
458 ### Image-Base-Magick ellipse: "$x1, $y1, $x2, $y2, $colour"
459  
460 if ($x1==$x2 || $y1==$y2) {
461 # ellipse of 1 pixel wide or high seems to draw nothing, dispatch to line()
462 $self->line($x1,$y1, $x2,$y2, $colour);
463  
464 } else {
465 my $w = $x2 - $x1;
466 my $h = $y2 - $y1;
467 ### more than 1 pixel wide and/or high, primitive=>ellipse ...
468 ### $w
469 ### $h
470 ### ellipse: (($x1+$x2)/2).','.(($y1+$y2)/2).' '.($w/2).','.($h/2).' 0,360'
471 if (my $err = $self->{'-imagemagick'}
472 ->Draw (primitive => 'ellipse',
473 strokewidth => 1,
474 ($fill ? 'fill' : 'stroke') => $colour,
475 points => ((($x1+$x2)/2).','.(($y1+$y2)/2)
476 .' '
477 .($w/2).','.($h/2)
478 .' 0,360'))) {
479 croak $err;
480 }
481 }
482 }
483  
484 sub diamond {
485 my ($self, $x1, $y1, $x2, $y2, $colour, $fill) = @_;
486 ### Image-Base-Magick diamond() ...
487  
488 my $xh = ($x2 - $x1);
489 my $yh = ($y2 - $y1);
490 my $xeven = ($xh & 1);
491 my $yeven = ($yh & 1);
492 $xh = int($xh / 2);
493 $yh = int($yh / 2);
494 ### x centre: $x1+$xh, $x2-$xh
495 ### assert: $x1+$xh+$xeven == $x2-$xh
496 ### assert: $y1+$yh+$yeven == $y2-$yh
497  
498 if ($x1==$x2 && $y1==$y2) {
499 # 1x1 polygon doesn't seem to draw any pixels in imagemagick 6.6, dispatch to xy()
500 $self->xy($x1,$y1, $colour);
501  
502 } elsif (my $err = $self->{'-imagemagick'}
503 ->Draw (primitive => 'polygon',
504 ($fill ? 'fill' : 'stroke') => $colour,
505 strokewidth => 0,
506 points => (($x1+$xh).' '.$y1 # top centre
507  
508 # left
509 .' '.$x1.' '.($y1+$yh)
510  
511 .($yeven ? ' '.$x1.' '.($y2-$yh) : '')
512  
513 # bottom
514 .' '.($x1+$xh).' '.$y2
515 .($xeven ? ' '.($x2-$xh).' '.$y2 : '')
516  
517 # right
518 .($yeven ? ' '.$x2.' '.($y2-$yh) : '')
519 .' '.$x2.' '.($y1+$yh)
520  
521 .($xeven ? ' '.($x2-$xh).' '.$y1 : '')
522 ))) {
523 croak $err;
524 }
525 }
526  
527 # sub add_colours {
528 # my $self = shift;
529 # ### add_colours: @_
530 #
531 # my $m = $self->{'-imagemagick'};
532 # }
533  
534 1;
535 __END__
↑ Summary