4 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS %formats $DEBUG %filters %DSOs $ERRSTR $fontstate %OPCODES $I2P $FORMATGUESS);
81 i_writetiff_wiol_faxable
148 $VERSION = '0.39pre1';
149 @ISA = qw(Exporter DynaLoader);
150 bootstrap Imager $VERSION;
154 i_init_fonts(); # Initialize font engines
155 Imager::Font::__init();
156 for(i_list_formats()) { $formats{$_}++; }
158 if ($formats{'t1'}) {
162 if (!$formats{'t1'} and !$formats{'tt'}
163 && !$formats{'ft2'} && !$formats{'w32'}) {
164 $fontstate='no font support';
167 %OPCODES=(Add=>[0],Sub=>[1],Mult=>[2],Div=>[3],Parm=>[4],'sin'=>[5],'cos'=>[6],'x'=>[4,0],'y'=>[4,1]);
171 # the members of the subhashes under %filters are:
172 # callseq - a list of the parameters to the underlying filter in the
173 # order they are passed
174 # callsub - a code ref that takes a named parameter list and calls the
176 # defaults - a hash of default values
177 # names - defines names for value of given parameters so if the names
178 # field is foo=> { bar=>1 }, and the user supplies "bar" as the
179 # foo parameter, the filter will receive 1 for the foo
182 callseq => ['image','intensity'],
183 callsub => sub { my %hsh=@_; i_contrast($hsh{image},$hsh{intensity}); }
187 callseq => ['image', 'amount', 'subtype'],
188 defaults => { amount=>3,subtype=>0 },
189 callsub => sub { my %hsh=@_; i_noise($hsh{image},$hsh{amount},$hsh{subtype}); }
192 $filters{hardinvert} ={
193 callseq => ['image'],
195 callsub => sub { my %hsh=@_; i_hardinvert($hsh{image}); }
198 $filters{autolevels} ={
199 callseq => ['image','lsat','usat','skew'],
200 defaults => { lsat=>0.1,usat=>0.1,skew=>0.0 },
201 callsub => sub { my %hsh=@_; i_autolevels($hsh{image},$hsh{lsat},$hsh{usat},$hsh{skew}); }
204 $filters{turbnoise} ={
205 callseq => ['image'],
206 defaults => { xo=>0.0,yo=>0.0,scale=>10.0 },
207 callsub => sub { my %hsh=@_; i_turbnoise($hsh{image},$hsh{xo},$hsh{yo},$hsh{scale}); }
210 $filters{radnoise} ={
211 callseq => ['image'],
212 defaults => { xo=>100,yo=>100,ascale=>17.0,rscale=>0.02 },
213 callsub => sub { my %hsh=@_; i_radnoise($hsh{image},$hsh{xo},$hsh{yo},$hsh{rscale},$hsh{ascale}); }
217 callseq => ['image', 'coef'],
219 callsub => sub { my %hsh=@_; i_conv($hsh{image},$hsh{coef}); }
223 callseq => ['image', 'xo', 'yo', 'colors', 'dist'],
225 callsub => sub { my %hsh=@_; i_gradgen($hsh{image}, $hsh{xo}, $hsh{yo}, $hsh{colors}, $hsh{dist}); }
228 $filters{nearest_color} ={
229 callseq => ['image', 'xo', 'yo', 'colors', 'dist'],
231 callsub => sub { my %hsh=@_; i_nearest_color($hsh{image}, $hsh{xo}, $hsh{yo}, $hsh{colors}, $hsh{dist}); }
233 $filters{gaussian} = {
234 callseq => [ 'image', 'stddev' ],
236 callsub => sub { my %hsh = @_; i_gaussian($hsh{image}, $hsh{stddev}); },
240 callseq => [ qw(image size) ],
241 defaults => { size => 20 },
242 callsub => sub { my %hsh = @_; i_mosaic($hsh{image}, $hsh{size}) },
246 callseq => [ qw(image bump elevation lightx lighty st) ],
247 defaults => { elevation=>0, st=> 2 },
250 i_bumpmap($hsh{image}, $hsh{bump}{IMG}, $hsh{elevation},
251 $hsh{lightx}, $hsh{lighty}, $hsh{st});
254 $filters{bumpmap_complex} =
256 callseq => [ qw(image bump channel tx ty Lx Ly Lz cd cs n Ia Il Is) ],
267 Ia => Imager::Color->new(rgb=>[0,0,0]),
268 Il => Imager::Color->new(rgb=>[255,255,255]),
269 Is => Imager::Color->new(rgb=>[255,255,255]),
273 i_bumpmap_complex($hsh{image}, $hsh{bump}{IMG}, $hsh{channel},
274 $hsh{tx}, $hsh{ty}, $hsh{Lx}, $hsh{Ly}, $hsh{Lz},
275 $hsh{cd}, $hsh{cs}, $hsh{n}, $hsh{Ia}, $hsh{Il},
279 $filters{postlevels} =
281 callseq => [ qw(image levels) ],
282 defaults => { levels => 10 },
283 callsub => sub { my %hsh = @_; i_postlevels($hsh{image}, $hsh{levels}); },
285 $filters{watermark} =
287 callseq => [ qw(image wmark tx ty pixdiff) ],
288 defaults => { pixdiff=>10, tx=>0, ty=>0 },
292 i_watermark($hsh{image}, $hsh{wmark}{IMG}, $hsh{tx}, $hsh{ty},
298 callseq => [ qw(image xa ya xb yb ftype repeat combine super_sample ssample_param segments) ],
300 ftype => { linear => 0,
306 repeat => { none => 0,
321 multiply => 2, mult => 2,
324 subtract => 5, sub => 5,
334 defaults => { ftype => 0, repeat => 0, combine => 0,
335 super_sample => 0, ssample_param => 4,
338 Imager::Color->new(0,0,0),
339 Imager::Color->new(255, 255, 255),
347 i_fountain($hsh{image}, $hsh{xa}, $hsh{ya}, $hsh{xb}, $hsh{yb},
348 $hsh{ftype}, $hsh{repeat}, $hsh{combine}, $hsh{super_sample},
349 $hsh{ssample_param}, $hsh{segments});
352 $filters{unsharpmask} =
354 callseq => [ qw(image stddev scale) ],
355 defaults => { stddev=>2.0, scale=>1.0 },
359 i_unsharp_mask($hsh{image}, $hsh{stddev}, $hsh{scale});
363 $FORMATGUESS=\&def_guess_type;
371 # NOTE: this might be moved to an import override later on
375 # (look through @_ for special tags, process, and remove them);
377 # print Dumper($pack);
382 my %parms=(loglevel=>1,@_);
384 init_log($parms{'log'},$parms{'loglevel'});
387 # if ($parms{T1LIB_CONFIG}) { $ENV{T1LIB_CONFIG}=$parms{T1LIB_CONFIG}; }
388 # if ( $ENV{T1LIB_CONFIG} and ( $fontstate eq 'missing conf' )) {
396 print "shutdown code\n";
397 # for(keys %instances) { $instances{$_}->DESTROY(); }
398 malloc_state(); # how do decide if this should be used? -- store something from the import
399 print "Imager exiting\n";
403 # Load a filter plugin
408 my ($DSO_handle,$str)=DSO_open($filename);
409 if (!defined($DSO_handle)) { $Imager::ERRSTR="Couldn't load plugin '$filename'\n"; return undef; }
410 my %funcs=DSO_funclist($DSO_handle);
411 if ($DEBUG) { print "loading module $filename\n"; $i=0; for(keys %funcs) { printf(" %2d: %s\n",$i++,$_); } }
413 for(keys %funcs) { if ($filters{$_}) { $ERRSTR="filter '$_' already exists\n"; DSO_close($DSO_handle); return undef; } }
415 $DSOs{$filename}=[$DSO_handle,\%funcs];
418 my $evstr="\$filters{'".$_."'}={".$funcs{$_}.'};';
419 $DEBUG && print "eval string:\n",$evstr,"\n";
431 if (!$DSOs{$filename}) { $ERRSTR="plugin '$filename' not loaded."; return undef; }
432 my ($DSO_handle,$funcref)=@{$DSOs{$filename}};
433 for(keys %{$funcref}) {
435 $DEBUG && print "unloading: $_\n";
437 my $rc=DSO_close($DSO_handle);
438 if (!defined($rc)) { $ERRSTR="unable to unload plugin '$filename'."; return undef; }
442 # take the results of i_error() and make a message out of it
444 return join(": ", map $_->[0], i_errors());
448 # Methods to be called on objects.
451 # Create a new Imager object takes very few parameters.
452 # usually you call this method and then call open from
453 # the resulting object
460 $self->{IMG}=undef; # Just to indicate what exists
461 $self->{ERRSTR}=undef; #
462 $self->{DEBUG}=$DEBUG;
463 $self->{DEBUG} && print "Initialized Imager\n";
464 if ($hsh{xsize} && $hsh{ysize}) { $self->img_set(%hsh); }
468 # Copy an entire image with no changes
469 # - if an image has magic the copy of it will not be magical
473 unless ($self->{IMG}) { $self->{ERRSTR}='empty input image'; return undef; }
475 my $newcopy=Imager->new();
476 $newcopy->{IMG}=i_img_new();
477 i_copy($newcopy->{IMG},$self->{IMG});
485 unless ($self->{IMG}) { $self->{ERRSTR}='empty input image'; return undef; }
486 my %input=(left=>0, top=>0, @_);
487 unless($input{img}) {
488 $self->{ERRSTR}="no source image";
491 $input{left}=0 if $input{left} <= 0;
492 $input{top}=0 if $input{top} <= 0;
494 my($r,$b)=i_img_info($src->{IMG});
496 i_copyto($self->{IMG}, $src->{IMG},
497 0,0, $r, $b, $input{left}, $input{top});
498 return $self; # What should go here??
501 # Crop an image - i.e. return a new image that is smaller
505 unless ($self->{IMG}) { $self->{ERRSTR}='empty input image'; return undef; }
506 my %hsh=(left=>0,right=>0,top=>0,bottom=>0,@_);
508 my ($w,$h,$l,$r,$b,$t)=($self->getwidth(),$self->getheight(),
509 @hsh{qw(left right bottom top)});
510 $l=0 if not defined $l;
511 $t=0 if not defined $t;
513 $r||=$l+delete $hsh{'width'} if defined $l and exists $hsh{'width'};
514 $b||=$t+delete $hsh{'height'} if defined $t and exists $hsh{'height'};
515 $l||=$r-delete $hsh{'width'} if defined $r and exists $hsh{'width'};
516 $t||=$b-delete $hsh{'height'} if defined $b and exists $hsh{'height'};
518 $r=$self->getwidth if not defined $r;
519 $b=$self->getheight if not defined $b;
521 ($l,$r)=($r,$l) if $l>$r;
522 ($t,$b)=($b,$t) if $t>$b;
525 $l=int(0.5+($w-$hsh{'width'})/2);
530 if ($hsh{'height'}) {
531 $b=int(0.5+($h-$hsh{'height'})/2);
532 $t=$h+$hsh{'height'};
534 $hsh{'height'}=$b-$t;
537 # print "l=$l, r=$r, h=$hsh{'width'}\n";
538 # print "t=$t, b=$b, w=$hsh{'height'}\n";
540 my $dst=Imager->new(xsize=>$hsh{'width'}, ysize=>$hsh{'height'}, channels=>$self->getchannels());
542 i_copyto($dst->{IMG},$self->{IMG},$l,$t,$r,$b,0,0);
546 # Sets an image to a certain size and channel number
547 # if there was previously data in the image it is discarded
552 my %hsh=(xsize=>100, ysize=>100, channels=>3, bits=>8, type=>'direct', @_);
554 if (defined($self->{IMG})) {
555 # let IIM_DESTROY destroy it, it's possible this image is
556 # referenced from a virtual image (like masked)
557 #i_img_destroy($self->{IMG});
561 if ($hsh{type} eq 'paletted' || $hsh{type} eq 'pseudo') {
562 $self->{IMG} = i_img_pal_new($hsh{xsize}, $hsh{ysize}, $hsh{channels},
563 $hsh{maxcolors} || 256);
565 elsif ($hsh{bits} == 16) {
566 $self->{IMG} = i_img_16_new($hsh{xsize}, $hsh{ysize}, $hsh{channels});
569 $self->{IMG}=Imager::ImgRaw::new($hsh{'xsize'}, $hsh{'ysize'},
574 # created a masked version of the current image
578 $self or return undef;
579 my %opts = (left => 0,
581 right => $self->getwidth,
582 bottom => $self->getheight,
584 my $mask = $opts{mask} ? $opts{mask}{IMG} : undef;
586 my $result = Imager->new;
587 $result->{IMG} = i_img_masked_new($self->{IMG}, $mask, $opts{left},
588 $opts{top}, $opts{right} - $opts{left},
589 $opts{bottom} - $opts{top});
590 # keep references to the mask and base images so they don't
592 $result->{DEPENDS} = [ $self->{IMG}, $mask ];
597 # convert an RGB image into a paletted image
601 if (@_ != 1 && !ref $_[0]) {
608 my $result = Imager->new;
609 $result->{IMG} = i_img_to_pal($self->{IMG}, $opts);
611 #print "Type ", i_img_type($result->{IMG}), "\n";
613 $result->{IMG} or undef $result;
618 # convert a paletted (or any image) to an 8-bit/channel RGB images
624 $result = Imager->new;
625 $result->{IMG} = i_img_to_rgb($self->{IMG})
634 my %opts = (colors=>[], @_);
636 @{$opts{colors}} or return undef;
638 $self->{IMG} and i_addcolors($self->{IMG}, @{$opts{colors}});
643 my %opts = (start=>0, colors=>[], @_);
644 @{$opts{colors}} or return undef;
646 $self->{IMG} and i_setcolors($self->{IMG}, $opts{start}, @{$opts{colors}});
652 if (!exists $opts{start} && !exists $opts{count}) {
655 $opts{count} = $self->colorcount;
657 elsif (!exists $opts{count}) {
660 elsif (!exists $opts{start}) {
665 return i_getcolors($self->{IMG}, $opts{start}, $opts{count});
669 i_colorcount($_[0]{IMG});
673 i_maxcolors($_[0]{IMG});
679 $opts{color} or return undef;
681 $self->{IMG} and i_findcolor($self->{IMG}, $opts{color});
686 $self->{IMG} and i_img_bits($self->{IMG});
692 return i_img_type($self->{IMG}) ? "paletted" : "direct";
698 $self->{IMG} and i_img_virtual($self->{IMG});
702 my ($self, %opts) = @_;
704 $self->{IMG} or return;
706 if (defined $opts{name}) {
710 while (defined($found = i_tags_find($self->{IMG}, $opts{name}, $start))) {
711 push @result, (i_tags_get($self->{IMG}, $found))[1];
714 return wantarray ? @result : $result[0];
716 elsif (defined $opts{code}) {
720 while (defined($found = i_tags_findn($self->{IMG}, $opts{code}, $start))) {
721 push @result, (i_tags_get($self->{IMG}, $found))[1];
728 return map { [ i_tags_get($self->{IMG}, $_) ] } 0.. i_tags_count($self->{IMG})-1;
731 return i_tags_count($self->{IMG});
740 return -1 unless $self->{IMG};
742 if (defined $opts{value}) {
743 if ($opts{value} =~ /^\d+$/) {
745 return i_tags_addn($self->{IMG}, $opts{name}, 0, $opts{value});
748 return i_tags_add($self->{IMG}, $opts{name}, 0, $opts{value}, 0);
751 elsif (defined $opts{data}) {
752 # force addition as a string
753 return i_tags_add($self->{IMG}, $opts{name}, 0, $opts{data}, 0);
756 $self->{ERRSTR} = "No value supplied";
760 elsif ($opts{code}) {
761 if (defined $opts{value}) {
762 if ($opts{value} =~ /^\d+$/) {
764 return i_tags_addn($self->{IMG}, $opts{code}, 0, $opts{value});
767 return i_tags_add($self->{IMG}, $opts{code}, 0, $opts{value}, 0);
770 elsif (defined $opts{data}) {
771 # force addition as a string
772 return i_tags_add($self->{IMG}, $opts{code}, 0, $opts{data}, 0);
775 $self->{ERRSTR} = "No value supplied";
788 return 0 unless $self->{IMG};
790 if (defined $opts{index}) {
791 return i_tags_delete($self->{IMG}, $opts{index});
793 elsif (defined $opts{name}) {
794 return i_tags_delbyname($self->{IMG}, $opts{name});
796 elsif (defined $opts{code}) {
797 return i_tags_delbycode($self->{IMG}, $opts{code});
800 $self->{ERRSTR} = "Need to supply index, name, or code parameter";
805 # Read an image from file
812 if (defined($self->{IMG})) {
813 # let IIM_DESTROY do the destruction, since the image may be
814 # referenced from elsewhere
815 #i_img_destroy($self->{IMG});
819 if (!$input{fd} and !$input{file} and !$input{data}) {
820 $self->{ERRSTR}='no file, fd or data parameter'; return undef;
823 $fh = new IO::File($input{file},"r");
825 $self->{ERRSTR}='Could not open file'; return undef;
834 # FIXME: Find the format here if not specified
835 # yes the code isn't here yet - next week maybe?
836 # Next week? Are you high or something? That comment
837 # has been there for half a year dude.
838 # Look, i just work here, ok?
840 if (!$input{type} and $input{file}) {
841 $input{type}=$FORMATGUESS->($input{file});
843 if (!$formats{$input{type}}) {
844 $self->{ERRSTR}='format not supported'; return undef;
847 my %iolready=(jpeg=>1, png=>1, tiff=>1, pnm=>1, raw=>1, bmp=>1, tga=>1);
849 if ($iolready{$input{type}}) {
851 $IO = io_new_fd($fd); # sort of simple for now eh?
853 if ( $input{type} eq 'jpeg' ) {
854 ($self->{IMG},$self->{IPTCRAW})=i_readjpeg_wiol( $IO );
855 if ( !defined($self->{IMG}) ) {
856 $self->{ERRSTR}='unable to read jpeg image'; return undef;
858 $self->{DEBUG} && print "loading a jpeg file\n";
862 if ( $input{type} eq 'tiff' ) {
863 $self->{IMG}=i_readtiff_wiol( $IO, -1 ); # Fixme, check if that length parameter is ever needed
864 if ( !defined($self->{IMG}) ) {
865 $self->{ERRSTR}='unable to read tiff image'; return undef;
867 $self->{DEBUG} && print "loading a tiff file\n";
871 if ( $input{type} eq 'pnm' ) {
872 $self->{IMG}=i_readpnm_wiol( $IO, -1 ); # Fixme, check if that length parameter is ever needed
873 if ( !defined($self->{IMG}) ) {
874 $self->{ERRSTR}='unable to read pnm image: '._error_as_msg(); return undef;
876 $self->{DEBUG} && print "loading a pnm file\n";
880 if ( $input{type} eq 'png' ) {
881 $self->{IMG}=i_readpng_wiol( $IO, -1 ); # Fixme, check if that length parameter is ever needed
882 if ( !defined($self->{IMG}) ) {
883 $self->{ERRSTR}='unable to read png image';
886 $self->{DEBUG} && print "loading a png file\n";
889 if ( $input{type} eq 'bmp' ) {
890 $self->{IMG}=i_readbmp_wiol( $IO );
891 if ( !defined($self->{IMG}) ) {
892 $self->{ERRSTR}='unable to read bmp image';
895 $self->{DEBUG} && print "loading a bmp file\n";
898 if ( $input{type} eq 'tga' ) {
899 $self->{IMG}=i_readtga_wiol( $IO, -1 ); # Fixme, check if that length parameter is ever needed
900 if ( !defined($self->{IMG}) ) {
901 $self->{ERRSTR}=$self->_error_as_msg();
902 # $self->{ERRSTR}='unable to read tga image';
905 $self->{DEBUG} && print "loading a tga file\n";
908 if ( $input{type} eq 'raw' ) {
909 my %params=(datachannels=>3,storechannels=>3,interleave=>1,%input);
911 if ( !($params{xsize} && $params{ysize}) ) {
912 $self->{ERRSTR}='missing xsize or ysize parameter for raw';
916 $self->{IMG} = i_readraw_wiol( $IO,
919 $params{datachannels},
920 $params{storechannels},
921 $params{interleave});
922 if ( !defined($self->{IMG}) ) {
923 $self->{ERRSTR}='unable to read raw image';
926 $self->{DEBUG} && print "loading a raw file\n";
931 # Old code for reference while changing the new stuff
933 if (!$input{type} and $input{file}) {
934 $input{type}=$FORMATGUESS->($input{file});
938 $self->{ERRSTR}='type parameter missing and not possible to guess from extension'; return undef;
941 if (!$formats{$input{type}}) {
942 $self->{ERRSTR}='format not supported';
947 $fh = new IO::File($input{file},"r");
949 $self->{ERRSTR}='Could not open file';
960 if ( $input{type} eq 'gif' ) {
962 if ($input{colors} && !ref($input{colors})) {
963 # must be a reference to a scalar that accepts the colour map
964 $self->{ERRSTR} = "option 'colors' must be a scalar reference";
967 if (exists $input{data}) {
968 if ($input{colors}) {
969 ($self->{IMG}, $colors) = i_readgif_scalar($input{data});
971 $self->{IMG}=i_readgif_scalar($input{data});
974 if ($input{colors}) {
975 ($self->{IMG}, $colors) = i_readgif( $fd );
977 $self->{IMG} = i_readgif( $fd )
981 # we may or may not change i_readgif to return blessed objects...
982 ${ $input{colors} } = [ map { NC(@$_) } @$colors ];
984 if ( !defined($self->{IMG}) ) {
985 $self->{ERRSTR}= 'reading GIF:'._error_as_msg();
988 $self->{DEBUG} && print "loading a gif file\n";
994 # Write an image to file
997 my %input=(jpegquality=>75, gifquant=>'mc', lmdither=>6.0, lmfixed=>[],
999 my ($fh, $rc, $fd, $IO);
1001 my %iolready=( tiff=>1, raw=>1, png=>1, pnm=>1, bmp=>1, jpeg=>1, tga=>1 ); # this will be SO MUCH BETTER once they are all in there
1003 unless ($self->{IMG}) { $self->{ERRSTR}='empty input image'; return undef; }
1005 if (!$input{file} and !$input{'fd'} and !$input{'data'}) { $self->{ERRSTR}='file/fd/data parameter missing'; return undef; }
1006 if (!$input{type} and $input{file}) { $input{type}=$FORMATGUESS->($input{file}); }
1007 if (!$input{type}) { $self->{ERRSTR}='type parameter missing and not possible to guess from extension'; return undef; }
1009 if (!$formats{$input{type}}) { $self->{ERRSTR}='format not supported'; return undef; }
1011 if (exists $input{'fd'}) {
1013 } elsif (exists $input{'data'}) {
1014 $IO = Imager::io_new_bufchain();
1016 $fh = new IO::File($input{file},"w+");
1017 if (!defined $fh) { $self->{ERRSTR}='Could not open file'; return undef; }
1018 binmode($fh) or die;
1019 $fd = $fh->fileno();
1022 if ($iolready{$input{type}}) {
1024 $IO = io_new_fd($fd);
1027 if ($input{type} eq 'tiff') {
1028 if (defined $input{class} && $input{class} eq 'fax') {
1029 if (!i_writetiff_wiol_faxable($self->{IMG}, $IO, $input{fax_fine})) {
1030 $self->{ERRSTR}='Could not write to buffer';
1034 if (!i_writetiff_wiol($self->{IMG}, $IO)) {
1035 $self->{ERRSTR}='Could not write to buffer';
1039 } elsif ( $input{type} eq 'pnm' ) {
1040 if ( ! i_writeppm_wiol($self->{IMG},$IO) ) {
1041 $self->{ERRSTR}='unable to write pnm image';
1044 $self->{DEBUG} && print "writing a pnm file\n";
1045 } elsif ( $input{type} eq 'raw' ) {
1046 if ( !i_writeraw_wiol($self->{IMG},$IO) ) {
1047 $self->{ERRSTR}='unable to write raw image';
1050 $self->{DEBUG} && print "writing a raw file\n";
1051 } elsif ( $input{type} eq 'png' ) {
1052 if ( !i_writepng_wiol($self->{IMG}, $IO) ) {
1053 $self->{ERRSTR}='unable to write png image';
1056 $self->{DEBUG} && print "writing a png file\n";
1057 } elsif ( $input{type} eq 'jpeg' ) {
1058 if ( !i_writejpeg_wiol($self->{IMG}, $IO, $input{jpegquality})) {
1059 $self->{ERRSTR} = $self->_error_as_msg();
1062 $self->{DEBUG} && print "writing a jpeg file\n";
1063 } elsif ( $input{type} eq 'bmp' ) {
1064 if ( !i_writebmp_wiol($self->{IMG}, $IO) ) {
1065 $self->{ERRSTR}='unable to write bmp image';
1068 $self->{DEBUG} && print "writing a bmp file\n";
1069 } elsif ( $input{type} eq 'tga' ) {
1070 if ( !i_writetga_wiol($self->{IMG}, $IO) ) {
1071 $self->{ERRSTR}=$self->_error_as_msg();
1072 # $self->{ERRSTR}='unable to write tga image';
1075 $self->{DEBUG} && print "writing a tga file\n";
1078 if (exists $input{'data'}) {
1079 my $data = io_slurp($IO);
1081 $self->{ERRSTR}='Could not slurp from buffer';
1084 ${$input{data}} = $data;
1088 if ( $input{type} eq 'gif' ) {
1089 if (not $input{gifplanes}) {
1091 my $count=i_count_colors($self->{IMG}, 256);
1092 $gp=8 if $count == -1;
1093 $gp=1 if not $gp and $count <= 2;
1094 $gp=2 if not $gp and $count <= 4;
1095 $gp=3 if not $gp and $count <= 8;
1096 $gp=4 if not $gp and $count <= 16;
1097 $gp=5 if not $gp and $count <= 32;
1098 $gp=6 if not $gp and $count <= 64;
1099 $gp=7 if not $gp and $count <= 128;
1100 $input{gifplanes} = $gp || 8;
1103 if ($input{gifplanes}>8) {
1104 $input{gifplanes}=8;
1106 if ($input{gifquant} eq 'gen' || $input{callback}) {
1109 if ($input{gifquant} eq 'lm') {
1111 $input{make_colors} = 'addi';
1112 $input{translate} = 'perturb';
1113 $input{perturb} = $input{lmdither};
1114 } elsif ($input{gifquant} eq 'gen') {
1115 # just pass options through
1117 $input{make_colors} = 'webmap'; # ignored
1118 $input{translate} = 'giflib';
1121 if ($input{callback}) {
1122 defined $input{maxbuffer} or $input{maxbuffer} = -1;
1123 $rc = i_writegif_callback($input{callback}, $input{maxbuffer},
1124 \%input, $self->{IMG});
1126 $rc = i_writegif_gen($fd, \%input, $self->{IMG});
1129 } elsif ($input{gifquant} eq 'lm') {
1130 $rc=i_writegif($self->{IMG},$fd,$input{gifplanes},$input{lmdither},$input{lmfixed});
1132 $rc=i_writegifmc($self->{IMG},$fd,$input{gifplanes});
1134 if ( !defined($rc) ) {
1135 $self->{ERRSTR} = "Writing GIF file: "._error_as_msg(); return undef;
1137 $self->{DEBUG} && print "writing a gif file\n";
1145 my ($class, $opts, @images) = @_;
1147 if ($opts->{type} eq 'gif') {
1148 my $gif_delays = $opts->{gif_delays};
1149 local $opts->{gif_delays} = $gif_delays;
1150 unless (ref $opts->{gif_delays}) {
1151 # assume the caller wants the same delay for each frame
1152 $opts->{gif_delays} = [ ($gif_delays) x @images ];
1154 # translate to ImgRaw
1155 if (grep !UNIVERSAL::isa($_, 'Imager') || !$_->{IMG}, @images) {
1156 $ERRSTR = "Usage: Imager->write_multi({ options }, @images)";
1159 my @work = map $_->{IMG}, @images;
1160 if ($opts->{callback}) {
1161 # Note: you may need to fix giflib for this one to work
1162 my $maxbuffer = $opts->{maxbuffer};
1163 defined $maxbuffer or $maxbuffer = -1; # max by default
1164 return i_writegif_callback($opts->{callback}, $maxbuffer,
1168 return i_writegif_gen($opts->{fd}, $opts, @work);
1171 my $fh = IO::File->new($opts->{file}, "w+");
1173 $ERRSTR = "Error creating $opts->{file}: $!";
1177 return i_writegif_gen(fileno($fh), $opts, @work);
1181 $ERRSTR = "Sorry, write_multi doesn't support $opts->{type} yet";
1186 # read multiple images from a file
1188 my ($class, %opts) = @_;
1190 if ($opts{file} && !exists $opts{type}) {
1192 my $type = $FORMATGUESS->($opts{file});
1193 $opts{type} = $type;
1195 unless ($opts{type}) {
1196 $ERRSTR = "No type parameter supplied and it couldn't be guessed";
1202 $file = IO::File->new($opts{file}, "r");
1204 $ERRSTR = "Could not open file $opts{file}: $!";
1208 $fd = fileno($file);
1211 $fd = fileno($opts{fh});
1213 $ERRSTR = "File handle specified with fh option not open";
1220 elsif ($opts{callback} || $opts{data}) {
1224 $ERRSTR = "You need to specify one of file, fd, fh, callback or data";
1228 if ($opts{type} eq 'gif') {
1231 @imgs = i_readgif_multi($fd);
1234 if (Imager::i_giflib_version() < 4.0) {
1235 $ERRSTR = "giflib3.x does not support callbacks";
1238 if ($opts{callback}) {
1239 @imgs = i_readgif_multi_callback($opts{callback})
1242 @imgs = i_readgif_multi_scalar($opts{data});
1247 bless { IMG=>$_, DEBUG=>$DEBUG, ERRSTR=>undef }, 'Imager'
1251 $ERRSTR = _error_as_msg();
1256 $ERRSTR = "Cannot read multiple images from $opts{type} files";
1260 # Destroy an Imager object
1264 # delete $instances{$self};
1265 if (defined($self->{IMG})) {
1266 # the following is now handled by the XS DESTROY method for
1267 # Imager::ImgRaw object
1268 # Re-enabling this will break virtual images
1269 # tested for in t/t020masked.t
1270 # i_img_destroy($self->{IMG});
1271 undef($self->{IMG});
1273 # print "Destroy Called on an empty image!\n"; # why did I put this here??
1277 # Perform an inplace filter of an image
1278 # that is the image will be overwritten with the data
1284 unless ($self->{IMG}) { $self->{ERRSTR}='empty input image'; return undef; }
1286 if (!$input{type}) { $self->{ERRSTR}='type parameter missing'; return undef; }
1288 if ( (grep { $_ eq $input{type} } keys %filters) != 1) {
1289 $self->{ERRSTR}='type parameter not matching any filter'; return undef;
1292 if ($filters{$input{type}}{names}) {
1293 my $names = $filters{$input{type}}{names};
1294 for my $name (keys %$names) {
1295 if (defined $input{$name} && exists $names->{$name}{$input{$name}}) {
1296 $input{$name} = $names->{$name}{$input{$name}};
1300 if (defined($filters{$input{type}}{defaults})) {
1301 %hsh=('image',$self->{IMG},%{$filters{$input{type}}{defaults}},%input);
1303 %hsh=('image',$self->{IMG},%input);
1306 my @cs=@{$filters{$input{type}}{callseq}};
1309 if (!defined($hsh{$_})) {
1310 $self->{ERRSTR}="missing parameter '$_' for filter ".$input{type}; return undef;
1314 &{$filters{$input{type}}{callsub}}(%hsh);
1318 $self->{DEBUG} && print "callseq is: @cs\n";
1319 $self->{DEBUG} && print "matching callseq is: @b\n";
1324 # Scale an image to requested size and return the scaled version
1328 my %opts=(scalefactor=>0.5,type=>'max',qtype=>'normal',@_);
1329 my $img = Imager->new();
1330 my $tmp = Imager->new();
1332 unless ($self->{IMG}) { $self->{ERRSTR}='empty input image'; return undef; }
1334 if ($opts{xpixels} and $opts{ypixels} and $opts{type}) {
1335 my ($xpix,$ypix)=( $opts{xpixels}/$self->getwidth() , $opts{ypixels}/$self->getheight() );
1336 if ($opts{type} eq 'min') { $opts{scalefactor}=min($xpix,$ypix); }
1337 if ($opts{type} eq 'max') { $opts{scalefactor}=max($xpix,$ypix); }
1338 } elsif ($opts{xpixels}) { $opts{scalefactor}=$opts{xpixels}/$self->getwidth(); }
1339 elsif ($opts{ypixels}) { $opts{scalefactor}=$opts{ypixels}/$self->getheight(); }
1341 if ($opts{qtype} eq 'normal') {
1342 $tmp->{IMG}=i_scaleaxis($self->{IMG},$opts{scalefactor},0);
1343 if ( !defined($tmp->{IMG}) ) { $self->{ERRSTR}='unable to scale image'; return undef; }
1344 $img->{IMG}=i_scaleaxis($tmp->{IMG},$opts{scalefactor},1);
1345 if ( !defined($img->{IMG}) ) { $self->{ERRSTR}='unable to scale image'; return undef; }
1348 if ($opts{'qtype'} eq 'preview') {
1349 $img->{IMG}=i_scale_nn($self->{IMG},$opts{'scalefactor'},$opts{'scalefactor'});
1350 if ( !defined($img->{IMG}) ) { $self->{ERRSTR}='unable to scale image'; return undef; }
1353 $self->{ERRSTR}='scale: invalid value for qtype'; return undef;
1356 # Scales only along the X axis
1360 my %opts=(scalefactor=>0.5,@_);
1362 unless ($self->{IMG}) { $self->{ERRSTR}='empty input image'; return undef; }
1364 my $img = Imager->new();
1366 if ($opts{pixels}) { $opts{scalefactor}=$opts{pixels}/$self->getwidth(); }
1368 unless ($self->{IMG}) { $self->{ERRSTR}='empty input image'; return undef; }
1369 $img->{IMG}=i_scaleaxis($self->{IMG},$opts{scalefactor},0);
1371 if ( !defined($img->{IMG}) ) { $self->{ERRSTR}='unable to scale image'; return undef; }
1375 # Scales only along the Y axis
1379 my %opts=(scalefactor=>0.5,@_);
1381 unless ($self->{IMG}) { $self->{ERRSTR}='empty input image'; return undef; }
1383 my $img = Imager->new();
1385 if ($opts{pixels}) { $opts{scalefactor}=$opts{pixels}/$self->getheight(); }
1387 unless ($self->{IMG}) { $self->{ERRSTR}='empty input image'; return undef; }
1388 $img->{IMG}=i_scaleaxis($self->{IMG},$opts{scalefactor},1);
1390 if ( !defined($img->{IMG}) ) { $self->{ERRSTR}='unable to scale image'; return undef; }
1395 # Transform returns a spatial transformation of the input image
1396 # this moves pixels to a new location in the returned image.
1397 # NOTE - should make a utility function to check transforms for
1402 unless ($self->{IMG}) { $self->{ERRSTR}='empty input image'; return undef; }
1404 my (@op,@ropx,@ropy,$iop,$or,@parm,$expr,@xt,@yt,@pt,$numre);
1406 # print Dumper(\%opts);
1409 if ( $opts{'xexpr'} and $opts{'yexpr'} ) {
1411 eval ("use Affix::Infix2Postfix;");
1414 $self->{ERRSTR}='transform: expr given and Affix::Infix2Postfix is not avaliable.';
1417 $I2P=Affix::Infix2Postfix->new('ops'=>[{op=>'+',trans=>'Add'},
1418 {op=>'-',trans=>'Sub'},
1419 {op=>'*',trans=>'Mult'},
1420 {op=>'/',trans=>'Div'},
1421 {op=>'-',type=>'unary',trans=>'u-'},
1423 {op=>'func',type=>'unary'}],
1424 'grouping'=>[qw( \( \) )],
1425 'func'=>[qw( sin cos )],
1430 @xt=$I2P->translate($opts{'xexpr'});
1431 @yt=$I2P->translate($opts{'yexpr'});
1433 $numre=$I2P->{'numre'};
1436 for(@xt) { if (/$numre/) { push(@pt,$_); push(@{$opts{'xopcodes'}},'Parm',$#pt); } else { push(@{$opts{'xopcodes'}},$_); } }
1437 for(@yt) { if (/$numre/) { push(@pt,$_); push(@{$opts{'yopcodes'}},'Parm',$#pt); } else { push(@{$opts{'yopcodes'}},$_); } }
1438 @{$opts{'parm'}}=@pt;
1441 # print Dumper(\%opts);
1443 if ( !exists $opts{'xopcodes'} or @{$opts{'xopcodes'}}==0) {
1444 $self->{ERRSTR}='transform: no xopcodes given.';
1448 @op=@{$opts{'xopcodes'}};
1450 if (!defined ($OPCODES{$iop}) and ($iop !~ /^\d+$/) ) {
1451 $self->{ERRSTR}="transform: illegal opcode '$_'.";
1454 push(@ropx,(exists $OPCODES{$iop}) ? @{$OPCODES{$iop}} : $iop );
1460 if ( !exists $opts{'yopcodes'} or @{$opts{'yopcodes'}}==0) {
1461 $self->{ERRSTR}='transform: no yopcodes given.';
1465 @op=@{$opts{'yopcodes'}};
1467 if (!defined ($OPCODES{$iop}) and ($iop !~ /^\d+$/) ) {
1468 $self->{ERRSTR}="transform: illegal opcode '$_'.";
1471 push(@ropy,(exists $OPCODES{$iop}) ? @{$OPCODES{$iop}} : $iop );
1476 if ( !exists $opts{'parm'}) {
1477 $self->{ERRSTR}='transform: no parameter arg given.';
1481 # print Dumper(\@ropx);
1482 # print Dumper(\@ropy);
1483 # print Dumper(\@ropy);
1485 my $img = Imager->new();
1486 $img->{IMG}=i_transform($self->{IMG},\@ropx,\@ropy,$opts{'parm'});
1487 if ( !defined($img->{IMG}) ) { $self->{ERRSTR}='transform: failed'; return undef; }
1495 my ($opts, @imgs) = @_;
1498 # this is fairly big, delay loading it
1499 eval "use Imager::Expr";
1504 $opts->{variables} = [ qw(x y) ];
1505 my ($width, $height) = @{$opts}{qw(width height)};
1507 $width ||= $imgs[0]->getwidth();
1508 $height ||= $imgs[0]->getheight();
1510 for my $img (@imgs) {
1511 $opts->{constants}{"w$img_num"} = $img->getwidth();
1512 $opts->{constants}{"h$img_num"} = $img->getheight();
1513 $opts->{constants}{"cx$img_num"} = $img->getwidth()/2;
1514 $opts->{constants}{"cy$img_num"} = $img->getheight()/2;
1519 $opts->{constants}{w} = $width;
1520 $opts->{constants}{cx} = $width/2;
1523 $Imager::ERRSTR = "No width supplied";
1527 $opts->{constants}{h} = $height;
1528 $opts->{constants}{cy} = $height/2;
1531 $Imager::ERRSTR = "No height supplied";
1534 my $code = Imager::Expr->new($opts);
1536 $Imager::ERRSTR = Imager::Expr::error();
1540 my $img = Imager->new();
1541 $img->{IMG} = i_transform2($opts->{width}, $opts->{height}, $code->code(),
1542 $code->nregs(), $code->cregs(),
1543 [ map { $_->{IMG} } @imgs ]);
1544 if (!defined $img->{IMG}) {
1545 $Imager::ERRSTR = "transform2 failed";
1555 my %opts=(tx=>0,ty=>0,@_);
1557 unless ($self->{IMG}) { $self->{ERRSTR}='empty input image'; return undef; }
1558 unless ($opts{src} && $opts{src}->{IMG}) { $self->{ERRSTR}='empty input image for source'; return undef; }
1560 unless (i_rubthru($self->{IMG}, $opts{src}->{IMG}, $opts{tx},$opts{ty})) {
1561 $self->{ERRSTR} = $self->_error_as_msg();
1571 my %xlate = (h=>0, v=>1, hv=>2, vh=>2);
1573 return () unless defined $opts{'dir'} and defined $xlate{$opts{'dir'}};
1574 $dir = $xlate{$opts{'dir'}};
1575 return $self if i_flipxy($self->{IMG}, $dir);
1582 if (defined $opts{right}) {
1583 my $degrees = $opts{right};
1585 $degrees += 360 * int(((-$degrees)+360)/360);
1587 $degrees = $degrees % 360;
1588 if ($degrees == 0) {
1589 return $self->copy();
1591 elsif ($degrees == 90 || $degrees == 180 || $degrees == 270) {
1592 my $result = Imager->new();
1593 if ($result->{IMG} = i_rotate90($self->{IMG}, $degrees)) {
1597 $self->{ERRSTR} = $self->_error_as_msg();
1602 $self->{ERRSTR} = "Parameter 'right' must be a multiple of 90 degrees";
1606 elsif (defined $opts{radians} || defined $opts{degrees}) {
1607 my $amount = $opts{radians} || $opts{degrees} * 3.1415926535 / 180;
1609 my $result = Imager->new;
1610 if ($result->{IMG} = i_rotate_exact($self->{IMG}, $amount)) {
1614 $self->{ERRSTR} = $self->_error_as_msg();
1619 $self->{ERRSTR} = "Only the 'right' parameter is available";
1624 sub matrix_transform {
1628 if ($opts{matrix}) {
1629 my $xsize = $opts{xsize} || $self->getwidth;
1630 my $ysize = $opts{ysize} || $self->getheight;
1632 my $result = Imager->new;
1633 $result->{IMG} = i_matrix_transform($self->{IMG}, $xsize, $ysize,
1640 $self->{ERRSTR} = "matrix parameter required";
1646 *yatf = \&matrix_transform;
1648 # These two are supported for legacy code only
1651 return Imager::Color->new(@_);
1655 return Imager::Color::set(@_);
1658 # Draws a box between the specified corner points.
1661 unless ($self->{IMG}) { $self->{ERRSTR}='empty input image'; return undef; }
1662 my $dflcl=i_color_new(255,255,255,255);
1663 my %opts=(color=>$dflcl,xmin=>0,ymin=>0,xmax=>$self->getwidth()-1,ymax=>$self->getheight()-1,@_);
1665 if (exists $opts{'box'}) {
1666 $opts{'xmin'} = min($opts{'box'}->[0],$opts{'box'}->[2]);
1667 $opts{'xmax'} = max($opts{'box'}->[0],$opts{'box'}->[2]);
1668 $opts{'ymin'} = min($opts{'box'}->[1],$opts{'box'}->[3]);
1669 $opts{'ymax'} = max($opts{'box'}->[1],$opts{'box'}->[3]);
1672 if ($opts{filled}) {
1673 i_box_filled($self->{IMG},$opts{xmin},$opts{ymin},$opts{xmax},
1674 $opts{ymax},$opts{color});
1676 elsif ($opts{fill}) {
1677 unless (UNIVERSAL::isa($opts{fill}, 'Imager::Fill')) {
1678 # assume it's a hash ref
1679 require 'Imager/Fill.pm';
1680 unless ($opts{fill} = Imager::Fill->new(%{$opts{fill}})) {
1681 $self->{ERRSTR} = $Imager::ERRSTR;
1685 i_box_cfill($self->{IMG},$opts{xmin},$opts{ymin},$opts{xmax},
1686 $opts{ymax},$opts{fill}{fill});
1689 i_box($self->{IMG},$opts{xmin},$opts{ymin},$opts{xmax},$opts{ymax},$opts{color});
1694 # Draws an arc - this routine SUCKS and is buggy - it sometimes doesn't work when the arc is a convex polygon
1698 unless ($self->{IMG}) { $self->{ERRSTR}='empty input image'; return undef; }
1699 my $dflcl=i_color_new(255,255,255,255);
1700 my %opts=(color=>$dflcl,
1701 'r'=>min($self->getwidth(),$self->getheight())/3,
1702 'x'=>$self->getwidth()/2,
1703 'y'=>$self->getheight()/2,
1704 'd1'=>0, 'd2'=>361, @_);
1706 unless (UNIVERSAL::isa($opts{fill}, 'Imager::Fill')) {
1707 # assume it's a hash ref
1708 require 'Imager/Fill.pm';
1709 $opts{fill} = Imager::Fill->new(%{$opts{fill}});
1711 i_arc_cfill($self->{IMG},$opts{'x'},$opts{'y'},$opts{'r'},$opts{'d1'},
1712 $opts{'d2'}, $opts{fill}{fill});
1715 if ($opts{d1} == 0 && $opts{d2} == 361 && $opts{aa}) {
1716 i_circle_aa($self->{IMG}, $opts{'x'}, $opts{'y'}, $opts{'r'},
1720 i_arc($self->{IMG},$opts{'x'},$opts{'y'},$opts{'r'},$opts{'d1'},
1721 $opts{'d2'},$opts{'color'});
1728 # Draws a line from one point to (but not including) the destination point
1732 my $dflcl=i_color_new(0,0,0,0);
1733 my %opts=(color=>$dflcl,@_);
1734 unless ($self->{IMG}) { $self->{ERRSTR}='empty input image'; return undef; }
1736 unless (exists $opts{x1} and exists $opts{y1}) { $self->{ERRSTR}='missing begining coord'; return undef; }
1737 unless (exists $opts{x2} and exists $opts{y2}) { $self->{ERRSTR}='missing ending coord'; return undef; }
1739 if ($opts{antialias}) {
1740 i_line_aa($self->{IMG},$opts{x1}, $opts{y1}, $opts{x2}, $opts{y2}, $opts{color});
1742 i_draw($self->{IMG},$opts{x1}, $opts{y1}, $opts{x2}, $opts{y2}, $opts{color});
1747 # Draws a line between an ordered set of points - It more or less just transforms this
1748 # into a list of lines.
1752 my ($pt,$ls,@points);
1753 my $dflcl=i_color_new(0,0,0,0);
1754 my %opts=(color=>$dflcl,@_);
1756 unless ($self->{IMG}) { $self->{ERRSTR}='empty input image'; return undef; }
1758 if (exists($opts{points})) { @points=@{$opts{points}}; }
1759 if (!exists($opts{points}) and exists($opts{'x'}) and exists($opts{'y'}) ) {
1760 @points=map { [ $opts{'x'}->[$_],$opts{'y'}->[$_] ] } (0..(scalar @{$opts{'x'}}-1));
1763 # print Dumper(\@points);
1765 if ($opts{antialias}) {
1767 if (defined($ls)) { i_line_aa($self->{IMG},$ls->[0],$ls->[1],$pt->[0],$pt->[1],$opts{color}); }
1772 if (defined($ls)) { i_draw($self->{IMG},$ls->[0],$ls->[1],$pt->[0],$pt->[1],$opts{color}); }
1779 # this the multipoint bezier curve
1780 # this is here more for testing that actual usage since
1781 # this is not a good algorithm. Usually the curve would be
1782 # broken into smaller segments and each done individually.
1786 my ($pt,$ls,@points);
1787 my $dflcl=i_color_new(0,0,0,0);
1788 my %opts=(color=>$dflcl,@_);
1790 unless ($self->{IMG}) { $self->{ERRSTR}='empty input image'; return undef; }
1792 if (exists $opts{points}) {
1793 $opts{'x'}=map { $_->[0]; } @{$opts{'points'}};
1794 $opts{'y'}=map { $_->[1]; } @{$opts{'points'}};
1797 unless ( @{$opts{'x'}} and @{$opts{'x'}} == @{$opts{'y'}} ) {
1798 $self->{ERRSTR}='Missing or invalid points.';
1802 i_bezier_multi($self->{IMG},$opts{'x'},$opts{'y'},$opts{'color'});
1808 my %opts = ( color=>Imager::Color->new(255, 255, 255), @_ );
1810 unless (exists $opts{x} && exists $opts{'y'}) {
1811 $self->{ERRSTR} = "missing seed x and y parameters";
1816 unless (UNIVERSAL::isa($opts{fill}, 'Imager::Fill')) {
1817 # assume it's a hash ref
1818 require 'Imager/Fill.pm';
1819 $opts{fill} = Imager::Fill->new(%{$opts{fill}});
1821 i_flood_cfill($self->{IMG}, $opts{x}, $opts{'y'}, $opts{fill}{fill});
1824 i_flood_fill($self->{IMG}, $opts{x}, $opts{'y'}, $opts{color});
1830 # make an identity matrix of the given size
1834 my $matrix = [ map { [ (0) x $size ] } 1..$size ];
1835 for my $c (0 .. ($size-1)) {
1836 $matrix->[$c][$c] = 1;
1841 # general function to convert an image
1843 my ($self, %opts) = @_;
1846 # the user can either specify a matrix or preset
1847 # the matrix overrides the preset
1848 if (!exists($opts{matrix})) {
1849 unless (exists($opts{preset})) {
1850 $self->{ERRSTR} = "convert() needs a matrix or preset";
1854 if ($opts{preset} eq 'gray' || $opts{preset} eq 'grey') {
1855 # convert to greyscale, keeping the alpha channel if any
1856 if ($self->getchannels == 3) {
1857 $matrix = [ [ 0.222, 0.707, 0.071 ] ];
1859 elsif ($self->getchannels == 4) {
1860 # preserve the alpha channel
1861 $matrix = [ [ 0.222, 0.707, 0.071, 0 ],
1866 $matrix = _identity($self->getchannels);
1869 elsif ($opts{preset} eq 'noalpha') {
1870 # strip the alpha channel
1871 if ($self->getchannels == 2 or $self->getchannels == 4) {
1872 $matrix = _identity($self->getchannels);
1873 pop(@$matrix); # lose the alpha entry
1876 $matrix = _identity($self->getchannels);
1879 elsif ($opts{preset} eq 'red' || $opts{preset} eq 'channel0') {
1881 $matrix = [ [ 1 ] ];
1883 elsif ($opts{preset} eq 'green' || $opts{preset} eq 'channel1') {
1884 $matrix = [ [ 0, 1 ] ];
1886 elsif ($opts{preset} eq 'blue' || $opts{preset} eq 'channel2') {
1887 $matrix = [ [ 0, 0, 1 ] ];
1889 elsif ($opts{preset} eq 'alpha') {
1890 if ($self->getchannels == 2 or $self->getchannels == 4) {
1891 $matrix = [ [ (0) x ($self->getchannels-1), 1 ] ];
1894 # the alpha is just 1 <shrug>
1895 $matrix = [ [ (0) x $self->getchannels, 1 ] ];
1898 elsif ($opts{preset} eq 'rgb') {
1899 if ($self->getchannels == 1) {
1900 $matrix = [ [ 1 ], [ 1 ], [ 1 ] ];
1902 elsif ($self->getchannels == 2) {
1903 # preserve the alpha channel
1904 $matrix = [ [ 1, 0 ], [ 1, 0 ], [ 1, 0 ], [ 0, 1 ] ];
1907 $matrix = _identity($self->getchannels);
1910 elsif ($opts{preset} eq 'addalpha') {
1911 if ($self->getchannels == 1) {
1912 $matrix = _identity(2);
1914 elsif ($self->getchannels == 3) {
1915 $matrix = _identity(4);
1918 $matrix = _identity($self->getchannels);
1922 $self->{ERRSTR} = "Unknown convert preset $opts{preset}";
1928 $matrix = $opts{matrix};
1931 my $new = Imager->new();
1932 $new->{IMG} = i_img_new();
1933 unless (i_convert($new->{IMG}, $self->{IMG}, $matrix)) {
1934 # most likely a bad matrix
1935 $self->{ERRSTR} = _error_as_msg();
1942 # general function to map an image through lookup tables
1945 my ($self, %opts) = @_;
1946 my @chlist = qw( red green blue alpha );
1948 if (!exists($opts{'maps'})) {
1949 # make maps from channel maps
1951 for $chnum (0..$#chlist) {
1952 if (exists $opts{$chlist[$chnum]}) {
1953 $opts{'maps'}[$chnum] = $opts{$chlist[$chnum]};
1954 } elsif (exists $opts{'all'}) {
1955 $opts{'maps'}[$chnum] = $opts{'all'};
1959 if ($opts{'maps'} and $self->{IMG}) {
1960 i_map($self->{IMG}, $opts{'maps'} );
1965 # destructive border - image is shrunk by one pixel all around
1968 my ($self,%opts)=@_;
1969 my($tx,$ty)=($self->getwidth()-1,$self->getheight()-1);
1970 $self->polyline('x'=>[0,$tx,$tx,0,0],'y'=>[0,0,$ty,$ty,0],%opts);
1974 # Get the width of an image
1978 if (!defined($self->{IMG})) { $self->{ERRSTR} = 'image is empty'; return undef; }
1979 return (i_img_info($self->{IMG}))[0];
1982 # Get the height of an image
1986 if (!defined($self->{IMG})) { $self->{ERRSTR} = 'image is empty'; return undef; }
1987 return (i_img_info($self->{IMG}))[1];
1990 # Get number of channels in an image
1994 if (!defined($self->{IMG})) { $self->{ERRSTR} = 'image is empty'; return undef; }
1995 return i_img_getchannels($self->{IMG});
2002 if (!defined($self->{IMG})) { $self->{ERRSTR} = 'image is empty'; return undef; }
2003 return i_img_getmask($self->{IMG});
2011 if (!defined($self->{IMG})) { $self->{ERRSTR} = 'image is empty'; return undef; }
2012 i_img_setmask( $self->{IMG} , $opts{mask} );
2015 # Get number of colors in an image
2019 my %opts=(maxcolors=>2**30,@_);
2020 if (!defined($self->{IMG})) { $self->{ERRSTR}='image is empty'; return undef; }
2021 my $rc=i_count_colors($self->{IMG},$opts{'maxcolors'});
2022 return ($rc==-1? undef : $rc);
2025 # draw string to an image
2029 unless ($self->{IMG}) { $self->{ERRSTR}='empty input image'; return undef; }
2031 my %input=('x'=>0, 'y'=>0, @_);
2032 $input{string}||=$input{text};
2034 unless(exists $input{string}) {
2035 $self->{ERRSTR}="missing required parameter 'string'";
2039 unless($input{font}) {
2040 $self->{ERRSTR}="missing required parameter 'font'";
2044 unless ($input{font}->draw(image=>$self, %input)) {
2045 $self->{ERRSTR} = $self->_error_as_msg();
2052 # Shortcuts that can be exported
2054 sub newcolor { Imager::Color->new(@_); }
2055 sub newfont { Imager::Font->new(@_); }
2057 *NC=*newcolour=*newcolor;
2064 #### Utility routines
2067 ref $_[0] ? $_[0]->{ERRSTR} : $ERRSTR
2070 # Default guess for the type of an image from extension
2072 sub def_guess_type {
2075 $ext=($name =~ m/\.([^\.]+)$/)[0];
2076 return 'tiff' if ($ext =~ m/^tiff?$/);
2077 return 'jpeg' if ($ext =~ m/^jpe?g$/);
2078 return 'pnm' if ($ext =~ m/^p[pgb]m$/);
2079 return 'png' if ($ext eq "png");
2080 return 'bmp' if ($ext eq "bmp" || $ext eq "dib");
2081 return 'tga' if ($ext eq "tga");
2082 return 'gif' if ($ext eq "gif");
2086 # get the minimum of a list
2090 for(@_) { if ($_<$mx) { $mx=$_; }}
2094 # get the maximum of a list
2098 for(@_) { if ($_>$mx) { $mx=$_; }}
2102 # string stuff for iptc headers
2106 $str = substr($str,3);
2107 $str =~ s/[\n\r]//g;
2114 # A little hack to parse iptc headers.
2119 my($caption,$photogr,$headln,$credit);
2121 my $str=$self->{IPTCRAW};
2125 @ar=split(/8BIM/,$str);
2130 @sar=split(/\034\002/);
2131 foreach $item (@sar) {
2132 if ($item =~ m/^x/) {
2133 $caption=&clean($item);
2136 if ($item =~ m/^P/) {
2137 $photogr=&clean($item);
2140 if ($item =~ m/^i/) {
2141 $headln=&clean($item);
2144 if ($item =~ m/^n/) {
2145 $credit=&clean($item);
2151 return (caption=>$caption,photogr=>$photogr,headln=>$headln,credit=>$credit);
2154 # Autoload methods go after =cut, and are processed by the autosplit program.
2158 # Below is the stub of documentation for your module. You better edit it!
2162 Imager - Perl extension for Generating 24 bit Images
2166 use Imager qw(init);
2169 $img = Imager->new();
2170 $img->open(file=>'image.ppm',type=>'pnm')
2171 || print "failed: ",$img->{ERRSTR},"\n";
2172 $scaled=$img->scale(xpixels=>400,ypixels=>400);
2173 $scaled->write(file=>'sc_image.ppm',type=>'pnm')
2174 || print "failed: ",$scaled->{ERRSTR},"\n";
2178 Imager is a module for creating and altering images - It is not meant
2179 as a replacement or a competitor to ImageMagick or GD. Both are
2180 excellent packages and well supported.
2184 Almost all functions take the parameters in the hash fashion.
2187 $img->open(file=>'lena.png',type=>'png');
2191 $img->open(file=>'lena.png');
2193 =head2 Basic concept
2195 An Image object is created with C<$img = Imager-E<gt>new()> Should
2196 this fail for some reason an explanation can be found in
2197 C<$Imager::ERRSTR> usually error messages are stored in
2198 C<$img-E<gt>{ERRSTR}>, but since no object is created this is the only
2199 way to give back errors. C<$Imager::ERRSTR> is also used to report
2200 all errors not directly associated with an image object. Examples:
2202 $img=Imager->new(); # This is an empty image (size is 0 by 0)
2203 $img->open(file=>'lena.png',type=>'png'); # initializes from file
2205 or if you want to create an empty image:
2207 $img=Imager->new(xsize=>400,ysize=>300,channels=>4);
2209 This example creates a completely black image of width 400 and
2210 height 300 and 4 channels.
2212 If you have an existing image, use img_set() to change it's dimensions
2213 - this will destroy any existing image data:
2215 $img->img_set(xsize=>500, ysize=>500, channels=>4);
2217 To create paletted images, set the 'type' parameter to 'paletted':
2219 $img = Imager->new(xsize=>200, ysize=>200, channels=>3, type=>'paletted');
2221 which creates an image with a maxiumum of 256 colors, which you can
2222 change by supplying the C<maxcolors> parameter.
2224 You can create a new paletted image from an existing image using the
2225 to_paletted() method:
2227 $palimg = $img->to_paletted(\%opts)
2229 where %opts contains the options specified under L<Quantization options>.
2231 You can convert a paletted image (or any image) to an 8-bit/channel
2234 $rgbimg = $img->to_rgb8;
2236 Warning: if you draw on a paletted image with colors that aren't in
2237 the palette, the image will be internally converted to a normal image.
2239 For improved color precision you can use the bits parameter to specify
2240 16 bites per channel:
2242 $img = Imager->new(xsize=>200, ysize=>200, channels=>3, bits=>16);
2244 Note that as of this writing all functions should work on 16-bit
2245 images, but at only 8-bit/channel precision.
2247 Currently only 8 and 16/bit per channel image types are available,
2248 this may change later.
2250 Color objects are created by calling the Imager::Color->new()
2253 $color = Imager::Color->new($red, $green, $blue);
2254 $color = Imager::Color->new($red, $green, $blue, $alpha);
2255 $color = Imager::Color->new("#C0C0FF"); # html color specification
2257 This object can then be passed to functions that require a color parameter.
2259 Coordinates in Imager have the origin in the upper left corner. The
2260 horizontal coordinate increases to the right and the vertical
2263 =head2 Reading and writing images
2265 C<$img-E<gt>read()> generally takes two parameters, 'file' and 'type'.
2266 If the type of the file can be determined from the suffix of the file
2267 it can be omitted. Format dependant parameters are: For images of
2268 type 'raw' two extra parameters are needed 'xsize' and 'ysize', if the
2269 'channel' parameter is omitted for type 'raw' it is assumed to be 3.
2270 gif and png images might have a palette are converted to truecolor bit
2271 when read. Alpha channel is preserved for png images irregardless of
2272 them being in RGB or gray colorspace. Similarly grayscale jpegs are
2273 one channel images after reading them. For jpeg images the iptc
2274 header information (stored in the APP13 header) is avaliable to some
2275 degree. You can get the raw header with C<$img-E<gt>{IPTCRAW}>, but
2276 you can also retrieve the most basic information with
2277 C<%hsh=$img-E<gt>parseiptc()> as always patches are welcome. pnm has no
2278 extra options. Examples:
2280 $img = Imager->new();
2281 $img->read(file=>"cover.jpg") or die $img->errstr; # gets type from name
2283 $img = Imager->new();
2284 { local(*FH,$/); open(FH,"file.gif") or die $!; $a=<FH>; }
2285 $img->read(data=>$a,type=>'gif') or die $img->errstr;
2287 The second example shows how to read an image from a scalar, this is
2288 usefull if your data originates from somewhere else than a filesystem
2289 such as a database over a DBI connection.
2291 When writing to a tiff image file you can also specify the 'class'
2292 parameter, which can currently take a single value, "fax". If class
2293 is set to fax then a tiff image which should be suitable for faxing
2294 will be written. For the best results start with a grayscale image.
2295 By default the image is written at fine resolution you can override
2296 this by setting the "fax_fine" parameter to 0.
2298 If you are reading from a gif image file, you can supply a 'colors'
2299 parameter which must be a reference to a scalar. The referenced
2300 scalar will receive an array reference which contains the colors, each
2301 represented as an Imager::Color object.
2303 If you already have an open file handle, for example a socket or a
2304 pipe, you can specify the 'fd' parameter instead of supplying a
2305 filename. Please be aware that you need to use fileno() to retrieve
2306 the file descriptor for the file:
2308 $img->read(fd=>fileno(FILE), type=>'gif') or die $img->errstr;
2310 For writing using the 'fd' option you will probably want to set $| for
2311 that descriptor, since the writes to the file descriptor bypass Perl's
2312 (or the C libraries) buffering. Setting $| should avoid out of order
2313 output. For example a common idiom when writing a CGI script is:
2315 # the $| _must_ come before you send the content-type
2317 print "Content-Type: image/jpeg\n\n";
2318 $img->write(fd=>fileno(STDOUT), type=>'jpeg') or die $img->errstr;
2320 *Note that load() is now an alias for read but will be removed later*
2322 C<$img-E<gt>write> has the same interface as C<read()>. The earlier
2323 comments on C<read()> for autodetecting filetypes apply. For jpegs
2324 quality can be adjusted via the 'jpegquality' parameter (0-100). The
2325 number of colorplanes in gifs are set with 'gifplanes' and should be
2326 between 1 (2 color) and 8 (256 colors). It is also possible to choose
2327 between two quantizing methods with the parameter 'gifquant'. If set
2328 to mc it uses the mediancut algorithm from either giflibrary. If set
2329 to lm it uses a local means algorithm. It is then possible to give
2330 some extra settings. lmdither is the dither deviation amount in pixels
2331 (manhattan distance). lmfixed can be an array ref who holds an array
2332 of Imager::Color objects. Note that the local means algorithm needs
2333 much more cpu time but also gives considerable better results than the
2334 median cut algorithm.
2336 Currently just for gif files, you can specify various options for the
2337 conversion from Imager's internal RGB format to the target's indexed
2338 file format. If you set the gifquant option to 'gen', you can use the
2339 options specified under L<Quantization options>.
2341 To see what Imager is compiled to support the following code snippet
2345 print "@{[keys %Imager::formats]}";
2347 When reading raw images you need to supply the width and height of the
2348 image in the xsize and ysize options:
2350 $img->read(file=>'foo.raw', xsize=>100, ysize=>100)
2351 or die "Cannot read raw image\n";
2353 If your input file has more channels than you want, or (as is common),
2354 junk in the fourth channel, you can use the datachannels and
2355 storechannels options to control the number of channels in your input
2356 file and the resulting channels in your image. For example, if your
2357 input image uses 32-bits per pixel with red, green, blue and junk
2358 values for each pixel you could do:
2360 $img->read(file=>'foo.raw', xsize=>100, ysize=>100, datachannels=>4,
2362 or die "Cannot read raw image\n";
2364 Normally the raw image is expected to have the value for channel 1
2365 immediately following channel 0 and channel 2 immediately following
2366 channel 1 for each pixel. If your input image has all the channel 0
2367 values for the first line of the image, followed by all the channel 1
2368 values for the first line and so on, you can use the interleave option:
2370 $img->read(file=>'foo.raw', xsize=100, ysize=>100, interleave=>1)
2371 or die "Cannot read raw image\n";
2373 =head2 Multi-image files
2375 Currently just for gif files, you can create files that contain more
2380 Imager->write_multi(\%opts, @images)
2382 Where %opts describes 4 possible types of outputs:
2388 This is C<gif> for gif animations.
2392 A code reference which is called with a single parameter, the data to
2393 be written. You can also specify $opts{maxbuffer} which is the
2394 maximum amount of data buffered. Note that there can be larger writes
2395 than this if the file library writes larger blocks. A smaller value
2396 maybe useful for writing to a socket for incremental display.
2400 The file descriptor to save the images to.
2404 The name of the file to write to.
2406 %opts may also include the keys from L<Gif options> and L<Quantization
2411 You must also specify the file format using the 'type' option.
2413 The current aim is to support other multiple image formats in the
2414 future, such as TIFF, and to support reading multiple images from a
2420 # ... code to put images in @images
2421 Imager->write_multi({type=>'gif',
2423 gif_delays=>[ (10) x @images ] },
2427 You can read multi-image files (currently only GIF files) using the
2428 read_multi() method:
2430 my @imgs = Imager->read_multi(file=>'foo.gif')
2431 or die "Cannot read images: ",Imager->errstr;
2433 The possible parameters for read_multi() are:
2439 The name of the file to read in.
2443 A filehandle to read in. This can be the name of a filehandle, but it
2444 will need the package name, no attempt is currently made to adjust
2445 this to the caller's package.
2449 The numeric file descriptor of an open file (or socket).
2453 A function to be called to read in data, eg. reading a blob from a
2454 database incrementally.
2458 The data of the input file in memory.
2462 The type of file. If the file is parameter is given and provides
2463 enough information to guess the type, then this parameter is optional.
2467 Note: you cannot use the callback or data parameter with giflib
2468 versions before 4.0.
2470 When reading from a GIF file with read_multi() the images are returned
2475 These options can be specified when calling write_multi() for gif
2476 files, when writing a single image with the gifquant option set to
2477 'gen', or for direct calls to i_writegif_gen and i_writegif_callback.
2479 Note that some viewers will ignore some of these options
2480 (gif_user_input in particular).
2484 =item gif_each_palette
2486 Each image in the gif file has it's own palette if this is non-zero.
2487 All but the first image has a local colour table (the first uses the
2488 global colour table.
2492 The images are written interlaced if this is non-zero.
2496 A reference to an array containing the delays between images, in 1/100
2499 If you want the same delay for every frame you can simply set this to
2500 the delay in 1/100 seconds.
2502 =item gif_user_input
2504 A reference to an array contains user input flags. If the given flag
2505 is non-zero the image viewer should wait for input before displaying
2510 A reference to an array of image disposal methods. These define what
2511 should be done to the image before displaying the next one. These are
2512 integers, where 0 means unspecified, 1 means the image should be left
2513 in place, 2 means restore to background colour and 3 means restore to
2516 =item gif_tran_color
2518 A reference to an Imager::Color object, which is the colour to use for
2519 the palette entry used to represent transparency in the palette. You
2520 need to set the transp option (see L<Quantization options>) for this
2525 A reference to an array of references to arrays which represent screen
2526 positions for each image.
2528 =item gif_loop_count
2530 If this is non-zero the Netscape loop extension block is generated,
2531 which makes the animation of the images repeat.
2533 This is currently unimplemented due to some limitations in giflib.
2535 =item gif_eliminate_unused
2537 If this is true, when you write a paletted image any unused colors
2538 will be eliminated from its palette. This is set by default.
2542 =head2 Quantization options
2544 These options can be specified when calling write_multi() for gif
2545 files, when writing a single image with the gifquant option set to
2546 'gen', or for direct calls to i_writegif_gen and i_writegif_callback.
2552 A arrayref of colors that are fixed. Note that some color generators
2557 The type of transparency processing to perform for images with an
2558 alpha channel where the output format does not have a proper alpha
2559 channel (eg. gif). This can be any of:
2565 No transparency processing is done. (default)
2569 Pixels more transparent that tr_threshold are rendered as transparent.
2573 An error diffusion dither is done on the alpha channel. Note that
2574 this is independent of the translation performed on the colour
2575 channels, so some combinations may cause undesired artifacts.
2579 The ordered dither specified by tr_orddith is performed on the alpha
2584 This will only be used if the image has an alpha channel, and if there
2585 is space in the palette for a transparency colour.
2589 The highest alpha value at which a pixel will be made transparent when
2590 transp is 'threshold'. (0-255, default 127)
2594 The type of error diffusion to perform on the alpha channel when
2595 transp is 'errdiff'. This can be any defined error diffusion type
2596 except for custom (see errdiff below).
2600 The type of ordered dither to perform on the alpha channel when transp
2601 is 'ordered'. Possible values are:
2607 A semi-random map is used. The map is the same each time.
2619 horizontal line dither.
2623 vertical line dither.
2629 diagonal line dither
2635 diagonal line dither
2639 dot matrix dither (currently the default). This is probably the best
2640 for displays (like web pages).
2644 A custom dither matrix is used - see tr_map
2650 When tr_orddith is custom this defines an 8 x 8 matrix of integers
2651 representing the transparency threshold for pixels corresponding to
2652 each position. This should be a 64 element array where the first 8
2653 entries correspond to the first row of the matrix. Values should be
2658 Defines how the quantization engine will build the palette(s).
2659 Currently this is ignored if 'translate' is 'giflib', but that may
2660 change. Possible values are:
2666 Only colors supplied in 'colors' are used.
2670 The web color map is used (need url here.)
2674 The original code for generating the color map (Addi's code) is used.
2678 Other methods may be added in the future.
2682 A arrayref containing Imager::Color objects, which represents the
2683 starting set of colors to use in translating the images. webmap will
2684 ignore this. The final colors used are copied back into this array
2685 (which is expanded if necessary.)
2689 The maximum number of colors to use in the image.
2693 The method used to translate the RGB values in the source image into
2694 the colors selected by make_colors. Note that make_colors is ignored
2695 whene translate is 'giflib'.
2697 Possible values are:
2703 The giflib native quantization function is used.
2707 The closest color available is used.
2711 The pixel color is modified by perturb, and the closest color is chosen.
2715 An error diffusion dither is performed.
2719 It's possible other transate values will be added.
2723 The type of error diffusion dither to perform. These values (except
2724 for custom) can also be used in tr_errdif.
2730 Floyd-Steinberg dither
2734 Jarvis, Judice and Ninke dither
2742 Custom. If you use this you must also set errdiff_width,
2743 errdiff_height and errdiff_map.
2749 =item errdiff_height
2755 When translate is 'errdiff' and errdiff is 'custom' these define a
2756 custom error diffusion map. errdiff_width and errdiff_height define
2757 the size of the map in the arrayref in errdiff_map. errdiff_orig is
2758 an integer which indicates the current pixel position in the top row
2763 When translate is 'perturb' this is the magnitude of the random bias
2764 applied to each channel of the pixel before it is looked up in the
2769 =head2 Obtaining/setting attributes of images
2771 To get the size of an image in pixels the C<$img-E<gt>getwidth()> and
2772 C<$img-E<gt>getheight()> are used.
2774 To get the number of channels in
2775 an image C<$img-E<gt>getchannels()> is used. $img-E<gt>getmask() and
2776 $img-E<gt>setmask() are used to get/set the channel mask of the image.
2778 $mask=$img->getmask();
2779 $img->setmask(mask=>1+2); # modify red and green only
2780 $img->setmask(mask=>8); # modify alpha only
2781 $img->setmask(mask=>$mask); # restore previous mask
2783 The mask of an image describes which channels are updated when some
2784 operation is performed on an image. Naturally it is not possible to
2785 apply masks to operations like scaling that alter the dimensions of
2788 It is possible to have Imager find the number of colors in an image
2789 by using C<$img-E<gt>getcolorcount()>. It requires memory proportionally
2790 to the number of colors in the image so it is possible to have it
2791 stop sooner if you only need to know if there are more than a certain number
2792 of colors in the image. If there are more colors than asked for
2793 the function return undef. Examples:
2795 if (!defined($img->getcolorcount(maxcolors=>512)) {
2796 print "Less than 512 colors in image\n";
2799 The bits() method retrieves the number of bits used to represent each
2800 channel in a pixel, typically 8. The type() method returns either
2801 'direct' for truecolor images or 'paletted' for paletted images. The
2802 virtual() method returns non-zero if the image contains no actual
2803 pixels, for example masked images.
2805 =head2 Paletted Images
2807 In general you can work with paletted images in the same way as RGB
2808 images, except that if you attempt to draw to a paletted image with a
2809 color that is not in the image's palette, the image will be converted
2810 to an RGB image. This means that drawing on a paletted image with
2811 anti-aliasing enabled will almost certainly convert the image to RGB.
2813 You can add colors to a paletted image with the addcolors() method:
2815 my @colors = ( Imager::Color->new(255, 0, 0),
2816 Imager::Color->new(0, 255, 0) );
2817 my $index = $img->addcolors(colors=>\@colors);
2819 The return value is the index of the first color added, or undef if
2820 adding the colors would overflow the palette.
2822 Once you have colors in the palette you can overwrite them with the
2825 $img->setcolors(start=>$start, colors=>\@colors);
2827 Returns true on success.
2829 To retrieve existing colors from the palette use the getcolors() method:
2831 # get the whole palette
2832 my @colors = $img->getcolors();
2833 # get a single color
2834 my $color = $img->getcolors(start=>$index);
2835 # get a range of colors
2836 my @colors = $img->getcolors(start=>$index, count=>$count);
2838 To quickly find a color in the palette use findcolor():
2840 my $index = $img->findcolor(color=>$color);
2842 which returns undef on failure, or the index of the color.
2844 You can get the current palette size with $img->colorcount, and the
2845 maximum size of the palette with $img->maxcolors.
2847 =head2 Drawing Methods
2849 IMPLEMENTATION MORE OR LESS DONE CHECK THE TESTS
2850 DOCUMENTATION OF THIS SECTION OUT OF SYNC
2852 It is possible to draw with graphics primitives onto images. Such
2853 primitives include boxes, arcs, circles and lines. A reference
2854 oriented list follows.
2857 $img->box(color=>$blue,xmin=>10,ymin=>30,xmax=>200,ymax=>300,filled=>1);
2859 The above example calls the C<box> method for the image and the box
2860 covers the pixels with in the rectangle specified. If C<filled> is
2861 ommited it is drawn as an outline. If any of the edges of the box are
2862 ommited it will snap to the outer edge of the image in that direction.
2863 Also if a color is omitted a color with (255,255,255,255) is used
2867 $img->arc(color=>$red, r=20, x=>200, y=>100, d1=>10, d2=>20 );
2869 This creates a filled red arc with a 'center' at (200, 100) and spans
2870 10 degrees and the slice has a radius of 20. SEE section on BUGS.
2872 Both the arc() and box() methods can take a C<fill> parameter which
2873 can either be an Imager::Fill object, or a reference to a hash
2874 containing the parameters used to create the fill:
2876 $img->box(xmin=>10, ymin=>30, xmax=>150, ymax=>60,
2877 fill => { hatch=>'cross2' });
2879 my $fill = Imager::Fill->new(hatch=>'stipple');
2880 $img->box(fill=>$fill);
2882 See L<Imager::Fill> for the type of fills you can use.
2885 $img->circle(color=>$green, r=50, x=>200, y=>100);
2887 This creates a green circle with its center at (200, 100) and has a
2891 $img->line(color=>$green, x1=10, x2=>100,
2892 y1=>20, y2=>50, antialias=>1 );
2894 That draws an antialiased line from (10,100) to (20,50).
2897 $img->polyline(points=>[[$x0,$y0],[$x1,$y1],[$x2,$y2]],color=>$red);
2898 $img->polyline(x=>[$x0,$x1,$x2], y=>[$y0,$y1,$y2], antialias=>1);
2900 Polyline is used to draw multilple lines between a series of points.
2901 The point set can either be specified as an arrayref to an array of
2902 array references (where each such array represents a point). The
2903 other way is to specify two array references.
2905 You can fill a region that all has the same color using the
2906 flood_fill() method, for example:
2908 $img->flood_fill(x=>50, y=>50, color=>$color);
2910 will fill all regions the same color connected to the point (50, 50).
2912 You can also use a general fill, so you could fill the same region
2913 with a check pattern using:
2915 $img->flood_fill(x=>50, y=>50, fill=>{ hatch=>'check2x2' });
2917 See L<Imager::Fill> for more information on general fills.
2919 =head2 Text rendering
2921 Text rendering is described in the Imager::Font manpage.
2923 =head2 Image resizing
2925 To scale an image so porportions are maintained use the
2926 C<$img-E<gt>scale()> method. if you give either a xpixels or ypixels
2927 parameter they will determine the width or height respectively. If
2928 both are given the one resulting in a larger image is used. example:
2929 C<$img> is 700 pixels wide and 500 pixels tall.
2931 $img->scale(xpixels=>400); # 400x285
2932 $img->scale(ypixels=>400); # 560x400
2934 $img->scale(xpixels=>400,ypixels=>400); # 560x400
2935 $img->scale(xpixels=>400,ypixels=>400,type=>min); # 400x285
2937 $img->scale(scalefactor=>0.25); 175x125 $img->scale(); # 350x250
2939 if you want to create low quality previews of images you can pass
2940 C<qtype=E<gt>'preview'> to scale and it will use nearest neighbor
2941 sampling instead of filtering. It is much faster but also generates
2942 worse looking images - especially if the original has a lot of sharp
2943 variations and the scaled image is by more than 3-5 times smaller than
2946 If you need to scale images per axis it is best to do it simply by
2947 calling scaleX and scaleY. You can pass either 'scalefactor' or
2948 'pixels' to both functions.
2950 Another way to resize an image size is to crop it. The parameters
2951 to crop are the edges of the area that you want in the returned image.
2952 If a parameter is omited a default is used instead.
2954 $newimg = $img->crop(left=>50, right=>100, top=>10, bottom=>100);
2955 $newimg = $img->crop(left=>50, top=>10, width=>50, height=>90);
2956 $newimg = $img->crop(left=>50, right=>100); # top
2958 You can also specify width and height parameters which will produce a
2959 new image cropped from the center of the input image, with the given
2962 $newimg = $img->crop(width=>50, height=>50);
2964 The width and height parameters take precedence over the left/right
2965 and top/bottom parameters respectively.
2967 =head2 Copying images
2969 To create a copy of an image use the C<copy()> method. This is usefull
2970 if you want to keep an original after doing something that changes the image
2971 inplace like writing text.
2975 To copy an image to onto another image use the C<paste()> method.
2977 $dest->paste(left=>40,top=>20,img=>$logo);
2979 That copies the entire C<$logo> image onto the C<$dest> image so that the
2980 upper left corner of the C<$logo> image is at (40,20).
2983 =head2 Flipping images
2985 An inplace horizontal or vertical flip is possible by calling the
2986 C<flip()> method. If the original is to be preserved it's possible to
2987 make a copy first. The only parameter it takes is the C<dir>
2988 parameter which can take the values C<h>, C<v>, C<vh> and C<hv>.
2990 $img->flip(dir=>"h"); # horizontal flip
2991 $img->flip(dir=>"vh"); # vertical and horizontal flip
2992 $nimg = $img->copy->flip(dir=>"v"); # make a copy and flip it vertically
2994 =head2 Rotating images
2996 Use the rotate() method to rotate an image.
2998 To rotate by an exact amount in degrees or radians, use the 'degrees'
2999 or 'radians' parameter:
3001 my $rot20 = $img->rotate(degrees=>20);
3002 my $rotpi4 = $img->rotate(radians=>3.14159265/4);
3004 To rotate in steps of 90 degrees, use the 'right' parameter:
3006 my $rotated = $img->rotate(right=>270);
3008 Rotations are clockwise for positive values.
3010 =head2 Blending Images
3012 To put an image or a part of an image directly
3013 into another it is best to call the C<paste()> method on the image you
3016 $img->paste(img=>$srcimage,left=>30,top=>50);
3018 That will take paste C<$srcimage> into C<$img> with the upper
3019 left corner at (30,50). If no values are given for C<left>
3020 or C<top> they will default to 0.
3022 A more complicated way of blending images is where one image is
3023 put 'over' the other with a certain amount of opaqueness. The
3024 method that does this is rubthrough.
3026 $img->rubthrough(src=>$srcimage,tx=>30,ty=>50);
3028 That will take the image C<$srcimage> and overlay it with the upper
3029 left corner at (30,50). You can rub 2 or 4 channel images onto a 3
3030 channel image, or a 2 channel image onto a 1 channel image. The last
3031 channel is used as an alpha channel.
3036 A special image method is the filter method. An example is:
3038 $img->filter(type=>'autolevels');
3040 This will call the autolevels filter. Here is a list of the filters
3041 that are always avaliable in Imager. This list can be obtained by
3042 running the C<filterlist.perl> script that comes with the module
3046 autolevels lsat(0.1) usat(0.1) skew(0)
3047 bumpmap bump elevation(0) lightx lighty st(2)
3048 bumpmap_complex bump channel(0) tx(0) ty(0) Lx(0.2) Ly(0.4)
3049 Lz(-1) cd(1.0) cs(40.0) n(1.3) Ia(0 0 0) Il(255 255 255)
3053 fountain xa ya xb yb ftype(linear) repeat(none) combine(none)
3054 super_sample(none) ssample_param(4) segments(see below)
3056 gradgen xo yo colors dist
3059 noise amount(3) subtype(0)
3060 postlevels levels(10)
3061 radnoise xo(100) yo(100) ascale(17.0) rscale(0.02)
3062 turbnoise xo(0.0) yo(0.0) scale(10.0)
3063 unsharpmask stddev(2.0) scale(1.0)
3064 watermark wmark pixdiff(10) tx(0) ty(0)
3066 The default values are in parenthesis. All parameters must have some
3067 value but if a parameter has a default value it may be omitted when
3068 calling the filter function.
3076 scales the value of each channel so that the values in the image will
3077 cover the whole possible range for the channel. I<lsat> and I<usat>
3078 truncate the range by the specified fraction at the top and bottom of
3079 the range respectivly..
3083 uses the channel I<elevation> image I<bump> as a bumpmap on your
3084 image, with the light at (I<lightx>, I<lightty>), with a shadow length
3087 =item bumpmap_complex
3089 uses the channel I<channel> image I<bump> as a bumpmap on your image.
3090 If Lz<0 the three L parameters are considered to be the direction of
3091 the light. If Lz>0 the L parameters are considered to be the light
3092 position. I<Ia> is the ambient colour, I<Il> is the light colour,
3093 I<Is> is the color of specular highlights. I<cd> is the diffuse
3094 coefficient and I<cs> is the specular coefficient. I<n> is the
3095 shininess of the surface.
3099 scales each channel by I<intensity>. Values of I<intensity> < 1.0
3100 will reduce the contrast.
3104 performs 2 1-dimensional convolutions on the image using the values
3105 from I<coef>. I<coef> should be have an odd length.
3109 renders a fountain fill, similar to the gradient tool in most paint
3110 software. The default fill is a linear fill from opaque black to
3111 opaque white. The points A(xa, ya) and B(xb, yb) control the way the
3112 fill is performed, depending on the ftype parameter:
3118 the fill ramps from A through to B.
3122 the fill ramps in both directions from A, where AB defines the length
3127 A is the center of a circle, and B is a point on it's circumference.
3128 The fill ramps from the center out to the circumference.
3132 A is the center of a square and B is the center of one of it's sides.
3133 This can be used to rotate the square. The fill ramps out to the
3134 edges of the square.
3138 A is the centre of a circle and B is a point on it's circumference. B
3139 marks the 0 and 360 point on the circle, with the fill ramping
3144 A is the center of a circle and B is a point on it's circumference. B
3145 marks the 0 and point on the circle, with the fill ramping in both
3146 directions to meet opposite.
3150 The I<repeat> option controls how the fill is repeated for some
3151 I<ftype>s after it leaves the AB range:
3157 no repeats, points outside of each range are treated as if they were
3158 on the extreme end of that range.
3162 the fill simply repeats in the positive direction
3166 the fill repeats in reverse and then forward and so on, in the
3171 the fill repeats in both the positive and negative directions (only
3172 meaningful for a linear fill).
3176 as for triangle, but in the negative direction too (only meaningful
3181 By default the fill simply overwrites the whole image (unless you have
3182 parts of the range 0 through 1 that aren't covered by a segment), if
3183 any segments of your fill have any transparency, you can set the
3184 I<combine> option to 'normal' to have the fill combined with the
3185 existing pixels. See the description of I<combine> in L<Imager/Fill>.
3187 If your fill has sharp edges, for example between steps if you use
3188 repeat set to 'triangle', you may see some aliased or ragged edges.
3189 You can enable super-sampling which will take extra samples within the
3190 pixel in an attempt anti-alias the fill.
3192 The possible values for the super_sample option are:
3198 no super-sampling is done
3202 a square grid of points are sampled. The number of points sampled is
3203 the square of ceil(0.5 + sqrt(ssample_param)).
3207 a random set of points within the pixel are sampled. This looks
3208 pretty bad for low ssample_param values.
3212 the points on the radius of a circle within the pixel are sampled.
3213 This seems to produce the best results, but is fairly slow (for now).
3217 You can control the level of sampling by setting the ssample_param
3218 option. This is roughly the number of points sampled, but depends on
3219 the type of sampling.
3221 The segments option is an arrayref of segments. You really should use
3222 the Imager::Fountain class to build your fountain fill. Each segment
3223 is an array ref containing:
3229 a floating point number between 0 and 1, the start of the range of fill parameters covered by this segment.
3233 a floating point number between start and end which can be used to
3234 push the color range towards one end of the segment.
3238 a floating point number between 0 and 1, the end of the range of fill
3239 parameters covered by this segment. This should be greater than
3246 The colors at each end of the segment. These can be either
3247 Imager::Color or Imager::Color::Float objects.
3251 The type of segment, this controls the way the fill parameter varies
3252 over the segment. 0 for linear, 1 for curved (unimplemented), 2 for
3253 sine, 3 for sphere increasing, 4 for sphere decreasing.
3257 The way the color varies within the segment, 0 for simple RGB, 1 for
3258 hue increasing and 2 for hue decreasing.
3262 Don't forgot to use Imager::Fountain instead of building your own.
3263 Really. It even loads GIMP gradient files.
3267 performs a gaussian blur of the image, using I<stddev> as the standard
3268 deviation of the curve used to combine pixels, larger values give
3269 bigger blurs. For a definition of Gaussian Blur, see:
3271 http://www.maths.abdn.ac.uk/~igc/tch/mx4002/notes/node99.html
3275 renders a gradient, with the given I<colors> at the corresponding
3276 points (x,y) in I<xo> and I<yo>. You can specify the way distance is
3277 measured for color blendeing by setting I<dist> to 0 for Euclidean, 1
3278 for Euclidean squared, and 2 for Manhattan distance.
3282 inverts the image, black to white, white to black. All channels are
3283 inverted, including the alpha channel if any.
3287 produces averaged tiles of the given I<size>.
3291 adds noise of the given I<amount> to the image. If I<subtype> is
3292 zero, the noise is even to each channel, otherwise noise is added to
3293 each channel independently.
3297 renders radiant Perlin turbulent noise. The centre of the noise is at
3298 (I<xo>, I<yo>), I<ascale> controls the angular scale of the noise ,
3299 and I<rscale> the radial scale, higher numbers give more detail.
3303 alters the image to have only I<levels> distinct level in each
3308 renders Perlin turbulent noise. (I<xo>, I<yo>) controls the origin of
3309 the noise, and I<scale> the scale of the noise, with lower numbers
3314 performs an unsharp mask on the image. This is the result of
3315 subtracting a gaussian blurred version of the image from the original.
3316 I<stddev> controls the stddev parameter of the gaussian blur. Each
3317 output pixel is: in + I<scale> * (in - blurred).
3321 applies I<wmark> as a watermark on the image with strength I<pixdiff>,
3322 with an origin at (I<tx>, I<ty>)
3326 A demonstration of most of the filters can be found at:
3328 http://www.develop-help.com/imager/filters.html
3330 (This is a slow link.)
3332 =head2 Color transformations
3334 You can use the convert method to transform the color space of an
3335 image using a matrix. For ease of use some presets are provided.
3337 The convert method can be used to:
3343 convert an RGB or RGBA image to grayscale.
3347 convert a grayscale image to RGB.
3351 extract a single channel from an image.
3355 set a given channel to a particular value (or from another channel)
3359 The currently defined presets are:
3367 converts an RGBA image into a grayscale image with alpha channel, or
3368 an RGB image into a grayscale image without an alpha channel.
3370 This weights the RGB channels at 22.2%, 70.7% and 7.1% respectively.
3374 removes the alpha channel from a 2 or 4 channel image. An identity
3381 extracts the first channel of the image into a single channel image
3387 extracts the second channel of the image into a single channel image
3393 extracts the third channel of the image into a single channel image
3397 extracts the alpha channel of the image into a single channel image.
3399 If the image has 1 or 3 channels (assumed to be grayscale of RGB) then
3400 the resulting image will be all white.
3404 converts a grayscale image to RGB, preserving the alpha channel if any
3408 adds an alpha channel to a grayscale or RGB image. Preserves an
3409 existing alpha channel for a 2 or 4 channel image.
3413 For example, to convert an RGB image into a greyscale image:
3415 $new = $img->convert(preset=>'grey'); # or gray
3417 or to convert a grayscale image to an RGB image:
3419 $new = $img->convert(preset=>'rgb');
3421 The presets aren't necessary simple constants in the code, some are
3422 generated based on the number of channels in the input image.
3424 If you want to perform some other colour transformation, you can use
3425 the 'matrix' parameter.
3427 For each output pixel the following matrix multiplication is done:
3429 channel[0] [ [ $c00, $c01, ... ] inchannel[0]
3430 [ ... ] = ... x [ ... ]
3431 channel[n-1] [ $cn0, ..., $cnn ] ] inchannel[max]
3434 So if you want to swap the red and green channels on a 3 channel image:
3436 $new = $img->convert(matrix=>[ [ 0, 1, 0 ],
3440 or to convert a 3 channel image to greyscale using equal weightings:
3442 $new = $img->convert(matrix=>[ [ 0.333, 0.333, 0.334 ] ])
3444 =head2 Color Mappings
3446 You can use the map method to map the values of each channel of an
3447 image independently using a list of lookup tables. It's important to
3448 realize that the modification is made inplace. The function simply
3449 returns the input image again or undef on failure.
3451 Each channel is mapped independently through a lookup table with 256
3452 entries. The elements in the table should not be less than 0 and not
3453 greater than 255. If they are out of the 0..255 range they are
3454 clamped to the range. If a table does not contain 256 entries it is
3457 Single channels can mapped by specifying their name and the mapping
3458 table. The channel names are C<red>, C<green>, C<blue>, C<alpha>.
3460 @map = map { int( $_/2 } 0..255;
3461 $img->map( red=>\@map );
3463 It is also possible to specify a single map that is applied to all
3464 channels, alpha channel included. For example this applies a gamma
3465 correction with a gamma of 1.4 to the input image.
3468 @map = map { int( 0.5 + 255*($_/255)**$gamma ) } 0..255;
3469 $img->map(all=> \@map);
3471 The C<all> map is used as a default channel, if no other map is
3472 specified for a channel then the C<all> map is used instead. If we
3473 had not wanted to apply gamma to the alpha channel we would have used:
3475 $img->map(all=> \@map, alpha=>[]);
3477 Since C<[]> contains fewer than 256 element the gamma channel is
3480 It is also possible to simply specify an array of maps that are
3481 applied to the images in the rgba order. For example to apply
3482 maps to the C<red> and C<blue> channels one would use:
3484 $img->map(maps=>[\@redmap, [], \@bluemap]);
3488 =head2 Transformations
3490 Another special image method is transform. It can be used to generate
3491 warps and rotations and such features. It can be given the operations
3492 in postfix notation or the module Affix::Infix2Postfix can be used.
3493 Look in the test case t/t55trans.t for an example.
3495 transform() needs expressions (or opcodes) that determine the source
3496 pixel for each target pixel. Source expressions are infix expressions
3497 using any of the +, -, *, / or ** binary operators, the - unary
3498 operator, ( and ) for grouping and the sin() and cos() functions. The
3499 target pixel is input as the variables x and y.
3501 You specify the x and y expressions as xexpr and yexpr respectively.
3502 You can also specify opcodes directly, but that's magic deep enough
3503 that you can look at the source code.
3505 You can still use the transform() function, but the transform2()
3506 function is just as fast and is more likely to be enhanced and
3509 Later versions of Imager also support a transform2() class method
3510 which allows you perform a more general set of operations, rather than
3511 just specifying a spatial transformation as with the transform()
3512 method, you can also perform colour transformations, image synthesis
3513 and image combinations.
3515 transform2() takes an reference to an options hash, and a list of
3516 images to operate one (this list may be empty):
3521 my $img = Imager::transform2(\%opts, @imgs)
3522 or die "transform2 failed: $Imager::ERRSTR";
3524 The options hash may define a transformation function, and optionally:
3530 width - the width of the image in pixels. If this isn't supplied the
3531 width of the first input image is used. If there are no input images
3536 height - the height of the image in pixels. If this isn't supplied
3537 the height of the first input image is used. If there are no input
3538 images an error occurs.
3542 constants - a reference to hash of constants to define for the
3543 expression engine. Some extra constants are defined by Imager
3547 The tranformation function is specified using either the expr or
3548 rpnexpr member of the options.
3552 =item Infix expressions
3554 You can supply infix expressions to transform 2 with the expr keyword.
3556 $opts{expr} = 'return getp1(w-x, h-y)'
3558 The 'expression' supplied follows this general grammar:
3560 ( identifier '=' expr ';' )* 'return' expr
3562 This allows you to simplify your expressions using variables.
3564 A more complex example might be:
3566 $opts{expr} = 'pix = getp1(x,y); return if(value(pix)>0.8,pix*0.8,pix)'
3568 Currently to use infix expressions you must have the Parse::RecDescent
3569 module installed (available from CPAN). There is also what might be a
3570 significant delay the first time you run the infix expression parser
3571 due to the compilation of the expression grammar.
3573 =item Postfix expressions
3575 You can supply postfix or reverse-polish notation expressions to
3576 transform2() through the rpnexpr keyword.
3578 The parser for rpnexpr emulates a stack machine, so operators will
3579 expect to see their parameters on top of the stack. A stack machine
3580 isn't actually used during the image transformation itself.
3582 You can store the value at the top of the stack in a variable called
3583 foo using !foo and retrieve that value again using @foo. The !foo
3584 notation will pop the value from the stack.
3586 An example equivalent to the infix expression above:
3588 $opts{rpnexpr} = 'x y getp1 !pix @pix value 0.8 gt @pix 0.8 * @pix ifp'
3592 transform2() has a fairly rich range of operators.
3596 =item +, *, -, /, %, **
3598 multiplication, addition, subtraction, division, remainder and
3599 exponentiation. Multiplication, addition and subtraction can be used
3600 on colour values too - though you need to be careful - adding 2 white
3601 values together and multiplying by 0.5 will give you grey, not white.
3603 Division by zero (or a small number) just results in a large number.
3604 Modulo zero (or a small number) results in zero.
3606 =item sin(N), cos(N), atan2(y,x)
3608 Some basic trig functions. They work in radians, so you can't just
3611 =item distance(x1, y1, x2, y2)
3613 Find the distance between two points. This is handy (along with
3614 atan2()) for producing circular effects.
3618 Find the square root. I haven't had much use for this since adding
3619 the distance() function.
3623 Find the absolute value.
3625 =item getp1(x,y), getp2(x,y), getp3(x, y)
3627 Get the pixel at position (x,y) from the first, second or third image
3628 respectively. I may add a getpn() function at some point, but this
3629 prevents static checking of the instructions against the number of
3630 images actually passed in.
3632 =item value(c), hue(c), sat(c), hsv(h,s,v)
3634 Separates a colour value into it's value (brightness), hue (colour)
3635 and saturation elements. Use hsv() to put them back together (after
3636 suitable manipulation).
3638 =item red(c), green(c), blue(c), rgb(r,g,b)
3640 Separates a colour value into it's red, green and blue colours. Use
3641 rgb(r,g,b) to put it back together.
3645 Convert a value to an integer. Uses a C int cast, so it may break on
3648 =item if(cond,ntrue,nfalse), if(cond,ctrue,cfalse)
3650 A simple (and inefficient) if function.
3652 =item <=,<,==,>=,>,!=
3654 Relational operators (typically used with if()). Since we're working
3655 with floating point values the equalities are 'near equalities' - an
3656 epsilon value is used.
3658 =item &&, ||, not(n)
3660 Basic logical operators.
3668 =item rpnexpr=>'x 25 % 15 * y 35 % 10 * getp1 !pat x y getp1 !pix @pix sat 0.7 gt @pat @pix ifp'
3670 tiles a smaller version of the input image over itself where the
3671 colour has a saturation over 0.7.
3673 =item rpnexpr=>'x 25 % 15 * y 35 % 10 * getp1 !pat y 360 / !rat x y getp1 1 @rat - pmult @pat @rat pmult padd'
3675 tiles the input image over itself so that at the top of the image the
3676 full-size image is at full strength and at the bottom the tiling is
3679 =item rpnexpr=>'x y getp1 !pix @pix value 0.96 gt @pix sat 0.1 lt and 128 128 255 rgb @pix ifp'
3681 replace pixels that are white or almost white with a palish blue
3683 =item rpnexpr=>'x 35 % 10 * y 45 % 8 * getp1 !pat x y getp1 !pix @pix sat 0.2 lt @pix value 0.9 gt and @pix @pat @pix value 2 / 0.5 + pmult ifp'
3685 Tiles the input image overitself where the image isn't white or almost
3688 =item rpnexpr=>'x y 160 180 distance !d y 180 - x 160 - atan2 !a @d 10 / @a + 3.1416 2 * % !a2 @a2 180 * 3.1416 / 1 @a2 sin 1 + 2 / hsv'
3692 =item rpnexpr=>'x y 160 180 distance !d y 180 - x 160 - atan2 !a @d 10 / @a + 3.1416 2 * % !a2 @a 180 * 3.1416 / 1 @a2 sin 1 + 2 / hsv'
3694 A spiral built on top of a colour wheel.
3698 For details on expression parsing see L<Imager::Expr>. For details on
3699 the virtual machine used to transform the images, see
3700 L<Imager::regmach.pod>.
3702 =head2 Matrix Transformations
3704 Rather than having to write code in a little language, you can use a
3705 matrix to perform transformations, using the matrix_transform()
3708 my $im2 = $im->matrix_transform(matrix=>[ -1, 0, $im->getwidth-1,
3712 By default the output image will be the same size as the input image,
3713 but you can supply the xsize and ysize parameters to change the size.
3715 Rather than building matrices by hand you can use the Imager::Matrix2d
3716 module to build the matrices. This class has methods to allow you to
3717 scale, shear, rotate, translate and reflect, and you can combine these
3718 with an overloaded multiplication operator.
3720 WARNING: the matrix you provide in the matrix operator transforms the
3721 co-ordinates within the B<destination> image to the co-ordinates
3722 within the I<source> image. This can be confusing.
3724 Since Imager has 3 different fairly general ways of transforming an
3725 image spatially, this method also has a yatf() alias. Yet Another
3726 Transformation Function.
3728 =head2 Masked Images
3730 Masked images let you control which pixels are modified in an
3731 underlying image. Where the first channel is completely black in the
3732 mask image, writes to the underlying image are ignored.
3734 For example, given a base image called $img:
3736 my $mask = Imager->new(xsize=>$img->getwidth, ysize=>getheight,
3738 # ... draw something on the mask
3739 my $maskedimg = $img->masked(mask=>$mask);
3741 You can specifiy the region of the underlying image that is masked
3742 using the left, top, right and bottom options.
3744 If you just want a subset of the image, without masking, just specify
3745 the region without specifying a mask.
3749 It is possible to add filters to the module without recompiling the
3750 module itself. This is done by using DSOs (Dynamic shared object)
3751 avaliable on most systems. This way you can maintain our own filters
3752 and not have to get me to add it, or worse patch every new version of
3753 the Module. Modules can be loaded AND UNLOADED at runtime. This
3754 means that you can have a server/daemon thingy that can do something
3757 load_plugin("dynfilt/dyntest.so") || die "unable to load plugin\n";
3758 %hsh=(a=>35,b=>200,type=>lin_stretch);
3760 unload_plugin("dynfilt/dyntest.so") || die "unable to load plugin\n";
3761 $img->write(type=>'pnm',file=>'testout/t60.jpg')
3762 || die "error in write()\n";
3764 Someone decides that the filter is not working as it should -
3765 dyntest.c modified and recompiled.
3767 load_plugin("dynfilt/dyntest.so") || die "unable to load plugin\n";
3770 An example plugin comes with the module - Please send feedback to
3771 addi@umich.edu if you test this.
3773 Note: This seems to test ok on the following systems:
3774 Linux, Solaris, HPUX, OpenBSD, FreeBSD, TRU64/OSF1, AIX.
3775 If you test this on other systems please let me know.
3779 Image tags contain meta-data about the image, ie. information not
3780 stored as pixels of the image.
3782 At the perl level each tag has a name or code and a value, which is an
3783 integer or an arbitrary string. An image can contain more than one
3784 tag with the same name or code.
3786 You can retrieve tags from an image using the tags() method, you can
3787 get all of the tags in an image, as a list of array references, with
3788 the code or name of the tag followed by the value of the tag:
3790 my @alltags = $img->tags;
3792 or you can get all tags that have a given name:
3794 my @namedtags = $img->tags(name=>$name);
3798 my @tags = $img->tags(code=>$code);
3800 You can add tags using the addtag() method, either by name:
3802 my $index = $img->addtag(name=>$name, value=>$value);
3806 my $index = $img->addtag(code=>$code, value=>$value);
3808 You can remove tags with the deltag() method, either by index:
3810 $img->deltag(index=>$index);
3814 $img->deltag(name=>$name);
3818 $img->deltag(code=>$code);
3820 In each case deltag() returns the number of tags deleted.
3822 When you read a GIF image using read_multi(), each image can include
3829 the offset of the image from the left of the "screen" ("Image Left
3834 the offset of the image from the top of the "screen" ("Image Top Position")
3838 non-zero if the image was interlaced ("Interlace Flag")
3840 =item gif_screen_width
3842 =item gif_screen_height
3844 the size of the logical screen ("Logical Screen Width",
3845 "Logical Screen Height")
3849 Non-zero if this image had a local color map.
3851 =item gif_background
3853 The index in the global colormap of the logical screen's background
3854 color. This is only set if the current image uses the global
3857 =item gif_trans_index
3859 The index of the color in the colormap used for transparency. If the
3860 image has a transparency then it is returned as a 4 channel image with
3861 the alpha set to zero in this palette entry. ("Transparent Color Index")
3865 The delay until the next frame is displayed, in 1/100 of a second.
3868 =item gif_user_input
3870 whether or not a user input is expected before continuing (view dependent)
3871 ("User Input Flag").
3875 how the next frame is displayed ("Disposal Method")
3879 the number of loops from the Netscape Loop extension. This may be zero.
3883 the first block of the first gif comment before each image.
3887 Where applicable, the ("name") is the name of that field from the GIF89
3890 The following tags are set in a TIFF image when read, and can be set
3895 =item tiff_resolutionunit
3897 The value of the ResolutionUnit tag. This is ignored on writing if
3898 the i_aspect_only tag is non-zero.
3902 The following tags are set when a Windows BMP file is read:
3906 =item bmp_compression
3908 The type of compression, if any.
3910 =item bmp_important_colors
3912 The number of important colors as defined by the writer of the image.
3916 Some standard tags will be implemented as time goes by:
3924 The spatial resolution of the image in pixels per inch. If the image
3925 format uses a different scale, eg. pixels per meter, then this value
3926 is converted. A floating point number stored as a string.
3930 If this is non-zero then the values in i_xres and i_yres are treated
3931 as a ratio only. If the image format does not support aspect ratios
3932 then this is scaled so the smaller value is 72dpi.
3938 box, arc, circle do not support antialiasing yet. arc, is only filled
3939 as of yet. Some routines do not return $self where they should. This
3940 affects code like this, C<$img-E<gt>box()-E<gt>arc()> where an object
3943 When saving Gif images the program does NOT try to shave of extra
3944 colors if it is possible. If you specify 128 colors and there are
3945 only 2 colors used - it will have a 128 colortable anyway.
3949 Arnar M. Hrafnkelsson, addi@umich.edu, and recently lots of assistance
3950 from Tony Cook. See the README for a complete list.
3954 perl(1), Imager::Color(3), Imager::Font(3), Imager::Matrix2d(3),
3955 Affix::Infix2Postfix(3), Parse::RecDescent(3)
3956 http://www.eecs.umich.edu/~addi/perl/Imager/