6 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS %formats $DEBUG %filters %DSOs $ERRSTR $fontstate %OPCODES $I2P $FORMATGUESS);
85 i_writetiff_wiol_faxable
156 @ISA = qw(Exporter DynaLoader);
157 bootstrap Imager $VERSION;
161 i_init_fonts(); # Initialize font engines
162 for(i_list_formats()) { $formats{$_}++; }
164 if ($formats{'t1'}) {
168 if (!$formats{'t1'} and !$formats{'tt'}) {
169 $fontstate='no font support';
172 %OPCODES=(Add=>[0],Sub=>[1],Mult=>[2],Div=>[3],Parm=>[4],'sin'=>[5],'cos'=>[6],'x'=>[4,0],'y'=>[4,1]);
177 callseq => ['image','intensity'],
178 callsub => sub { my %hsh=@_; i_contrast($hsh{image},$hsh{intensity}); }
182 callseq => ['image', 'amount', 'subtype'],
183 defaults => { amount=>3,subtype=>0 },
184 callsub => sub { my %hsh=@_; i_noise($hsh{image},$hsh{amount},$hsh{subtype}); }
187 $filters{hardinvert} ={
188 callseq => ['image'],
190 callsub => sub { my %hsh=@_; i_hardinvert($hsh{image}); }
193 $filters{autolevels} ={
194 callseq => ['image','lsat','usat','skew'],
195 defaults => { lsat=>0.1,usat=>0.1,skew=>0.0 },
196 callsub => sub { my %hsh=@_; i_autolevels($hsh{image},$hsh{lsat},$hsh{usat},$hsh{skew}); }
199 $filters{turbnoise} ={
200 callseq => ['image'],
201 defaults => { xo=>0.0,yo=>0.0,scale=>10.0 },
202 callsub => sub { my %hsh=@_; i_turbnoise($hsh{image},$hsh{xo},$hsh{yo},$hsh{scale}); }
205 $filters{radnoise} ={
206 callseq => ['image'],
207 defaults => { xo=>100,yo=>100,ascale=>17.0,rscale=>0.02 },
208 callsub => sub { my %hsh=@_; i_radnoise($hsh{image},$hsh{xo},$hsh{yo},$hsh{rscale},$hsh{ascale}); }
212 callseq => ['image', 'coef'],
214 callsub => sub { my %hsh=@_; i_conv($hsh{image},$hsh{coef}); }
218 callseq => ['image', 'xo', 'yo', 'colors', 'dist'],
220 callsub => sub { my %hsh=@_; i_gradgen($hsh{image}, $hsh{xo}, $hsh{yo}, $hsh{colors}, $hsh{dist}); }
223 $filters{nearest_color} ={
224 callseq => ['image', 'xo', 'yo', 'colors', 'dist'],
226 callsub => sub { my %hsh=@_; i_nearest_color($hsh{image}, $hsh{xo}, $hsh{yo}, $hsh{colors}, $hsh{dist}); }
229 $FORMATGUESS=\&def_guess_type;
237 # NOTE: this might be moved to an import override later on
241 # (look through @_ for special tags, process, and remove them);
243 # print Dumper($pack);
248 my %parms=(loglevel=>1,@_);
250 init_log($parms{'log'},$parms{'loglevel'});
253 # if ($parms{T1LIB_CONFIG}) { $ENV{T1LIB_CONFIG}=$parms{T1LIB_CONFIG}; }
254 # if ( $ENV{T1LIB_CONFIG} and ( $fontstate eq 'missing conf' )) {
262 print "shutdown code\n";
263 # for(keys %instances) { $instances{$_}->DESTROY(); }
264 malloc_state(); # how do decide if this should be used? -- store something from the import
265 print "Imager exiting\n";
269 # Load a filter plugin
274 my ($DSO_handle,$str)=DSO_open($filename);
275 if (!defined($DSO_handle)) { $Imager::ERRSTR="Couldn't load plugin '$filename'\n"; return undef; }
276 my %funcs=DSO_funclist($DSO_handle);
277 if ($DEBUG) { print "loading module $filename\n"; $i=0; for(keys %funcs) { printf(" %2d: %s\n",$i++,$_); } }
279 for(keys %funcs) { if ($filters{$_}) { $ERRSTR="filter '$_' already exists\n"; DSO_close($DSO_handle); return undef; } }
281 $DSOs{$filename}=[$DSO_handle,\%funcs];
284 my $evstr="\$filters{'".$_."'}={".$funcs{$_}.'};';
285 $DEBUG && print "eval string:\n",$evstr,"\n";
297 if (!$DSOs{$filename}) { $ERRSTR="plugin '$filename' not loaded."; return undef; }
298 my ($DSO_handle,$funcref)=@{$DSOs{$filename}};
299 for(keys %{$funcref}) {
301 $DEBUG && print "unloading: $_\n";
303 my $rc=DSO_close($DSO_handle);
304 if (!defined($rc)) { $ERRSTR="unable to unload plugin '$filename'."; return undef; }
308 # take the results of i_error() and make a message out of it
310 return join(": ", map $_->[0], i_errors());
315 # Methods to be called on objects.
318 # Create a new Imager object takes very few parameters.
319 # usually you call this method and then call open from
320 # the resulting object
327 $self->{IMG}=undef; # Just to indicate what exists
328 $self->{ERRSTR}=undef; #
329 $self->{DEBUG}=$DEBUG;
330 $self->{DEBUG} && print "Initialized Imager\n";
331 if ($hsh{xsize} && $hsh{ysize}) { $self->img_set(%hsh); }
336 # Copy an entire image with no changes
337 # - if an image has magic the copy of it will not be magical
341 unless ($self->{IMG}) { $self->{ERRSTR}='empty input image'; return undef; }
343 my $newcopy=Imager->new();
344 $newcopy->{IMG}=i_img_new();
345 i_copy($newcopy->{IMG},$self->{IMG});
353 unless ($self->{IMG}) { $self->{ERRSTR}='empty input image'; return undef; }
354 my %input=(left=>0, top=>0, @_);
355 unless($input{img}) {
356 $self->{ERRSTR}="no source image";
359 $input{left}=0 if $input{left} <= 0;
360 $input{top}=0 if $input{top} <= 0;
362 my($r,$b)=i_img_info($src->{IMG});
364 i_copyto($self->{IMG}, $src->{IMG},
365 0,0, $r, $b, $input{left}, $input{top});
366 return $self; # What should go here??
369 # Crop an image - i.e. return a new image that is smaller
373 unless ($self->{IMG}) { $self->{ERRSTR}='empty input image'; return undef; }
374 my %hsh=(left=>0,right=>0,top=>0,bottom=>0,@_);
376 my ($w,$h,$l,$r,$b,$t)=($self->getwidth(),$self->getheight(),
377 @hsh{qw(left right bottom top)});
378 $l=0 if not defined $l;
379 $t=0 if not defined $t;
381 $r||=$l+delete $hsh{'width'} if defined $l and exists $hsh{'width'};
382 $b||=$t+delete $hsh{'height'} if defined $t and exists $hsh{'height'};
383 $l||=$r-delete $hsh{'width'} if defined $r and exists $hsh{'width'};
384 $t||=$b-delete $hsh{'height'} if defined $b and exists $hsh{'height'};
386 $r=$self->getwidth if not defined $r;
387 $b=$self->getheight if not defined $b;
389 ($l,$r)=($r,$l) if $l>$r;
390 ($t,$b)=($b,$t) if $t>$b;
393 $l=int(0.5+($w-$hsh{'width'})/2);
398 if ($hsh{'height'}) {
399 $b=int(0.5+($h-$hsh{'height'})/2);
400 $t=$h+$hsh{'height'};
402 $hsh{'height'}=$b-$t;
405 # print "l=$l, r=$r, h=$hsh{'width'}\n";
406 # print "t=$t, b=$b, w=$hsh{'height'}\n";
408 my $dst=Imager->new(xsize=>$hsh{'width'}, ysize=>$hsh{'height'}, channels=>$self->getchannels());
410 i_copyto($dst->{IMG},$self->{IMG},$l,$t,$r,$b,0,0);
414 # Sets an image to a certain size and channel number
415 # if there was previously data in the image it is discarded
420 my %hsh=(xsize=>100,ysize=>100,channels=>3,@_);
422 if (defined($self->{IMG})) {
423 i_img_destroy($self->{IMG});
427 $self->{IMG}=Imager::ImgRaw::new($hsh{'xsize'},$hsh{'ysize'},$hsh{'channels'});
430 # Read an image from file
437 if (defined($self->{IMG})) {
438 i_img_destroy($self->{IMG});
442 if (!$input{fd} and !$input{file} and !$input{data}) {
443 $self->{ERRSTR}='no file, fd or data parameter'; return undef;
446 $fh = new IO::File($input{file},"r");
448 $self->{ERRSTR}='Could not open file'; return undef;
457 # FIXME: Find the format here if not specified
458 # yes the code isn't here yet - next week maybe?
459 # Next week? Are you high or something? That comment
460 # has been there for half a year dude.
463 if (!$input{type} and $input{file}) {
464 $input{type}=$FORMATGUESS->($input{file});
466 if (!$formats{$input{type}}) {
467 $self->{ERRSTR}='format not supported'; return undef;
470 my %iolready=(jpeg=>1, png=>1, tiff=>1, pnm=>1, raw=>1);
472 if ($iolready{$input{type}}) {
474 $IO = io_new_fd($fd); # sort of simple for now eh?
476 if ( $input{type} eq 'jpeg' ) {
477 ($self->{IMG},$self->{IPTCRAW})=i_readjpeg_wiol( $IO );
478 if ( !defined($self->{IMG}) ) {
479 $self->{ERRSTR}='unable to read jpeg image'; return undef;
481 $self->{DEBUG} && print "loading a jpeg file\n";
485 if ( $input{type} eq 'tiff' ) {
486 $self->{IMG}=i_readtiff_wiol( $IO, -1 ); # Fixme, check if that length parameter is ever needed
487 if ( !defined($self->{IMG}) ) {
488 $self->{ERRSTR}='unable to read tiff image'; return undef;
490 $self->{DEBUG} && print "loading a tiff file\n";
494 if ( $input{type} eq 'pnm' ) {
495 $self->{IMG}=i_readpnm_wiol( $IO, -1 ); # Fixme, check if that length parameter is ever needed
496 if ( !defined($self->{IMG}) ) {
497 $self->{ERRSTR}='unable to read pnm image: '._error_as_msg(); return undef;
499 $self->{DEBUG} && print "loading a pnm file\n";
503 if ( $input{type} eq 'png' ) {
504 $self->{IMG}=i_readpng_wiol( $IO, -1 ); # Fixme, check if that length parameter is ever needed
505 if ( !defined($self->{IMG}) ) {
506 $self->{ERRSTR}='unable to read png image';
509 $self->{DEBUG} && print "loading a png file\n";
512 if ( $input{type} eq 'raw' ) {
513 my %params=(datachannels=>3,storechannels=>3,interleave=>1,%input);
515 if ( !($params{xsize} && $params{ysize}) ) {
516 $self->{ERRSTR}='missing xsize or ysize parameter for raw';
520 $self->{IMG} = i_readraw_wiol( $IO,
523 $params{datachannels},
524 $params{storechannels},
525 $params{interleave});
526 if ( !defined($self->{IMG}) ) {
527 $self->{ERRSTR}='unable to read raw image';
530 $self->{DEBUG} && print "loading a raw file\n";
535 # Old code for reference while changing the new stuff
538 if (!$input{type} and $input{file}) {
539 $input{type}=$FORMATGUESS->($input{file});
543 $self->{ERRSTR}='type parameter missing and not possible to guess from extension'; return undef;
546 if (!$formats{$input{type}}) {
547 $self->{ERRSTR}='format not supported';
552 $fh = new IO::File($input{file},"r");
554 $self->{ERRSTR}='Could not open file';
565 if ( $input{type} eq 'gif' ) {
567 if ($input{colors} && !ref($input{colors})) {
568 # must be a reference to a scalar that accepts the colour map
569 $self->{ERRSTR} = "option 'colors' must be a scalar reference";
572 if (exists $input{data}) {
573 if ($input{colors}) {
574 ($self->{IMG}, $colors) = i_readgif_scalar($input{data});
576 $self->{IMG}=i_readgif_scalar($input{data});
579 if ($input{colors}) {
580 ($self->{IMG}, $colors) = i_readgif( $fd );
582 $self->{IMG} = i_readgif( $fd )
586 # we may or may not change i_readgif to return blessed objects...
587 ${ $input{colors} } = [ map { NC(@$_) } @$colors ];
589 if ( !defined($self->{IMG}) ) {
590 $self->{ERRSTR}= 'reading GIF:'._error_as_msg();
593 $self->{DEBUG} && print "loading a gif file\n";
596 if ( $input{type} eq 'jpeg' ) {
597 if ( !i_writejpeg_wiol($self->{IMG}, $IO, $input{jpegquality})) {
598 $self->{ERRSTR}='unable to write jpeg image';
601 $self->{DEBUG} && print "writing a jpeg file\n";
609 # Write an image to file
613 my %input=(jpegquality=>75, gifquant=>'mc', lmdither=>6.0, lmfixed=>[],
615 my ($fh, $rc, $fd, $IO);
617 my %iolready=( tiff=>1, raw=>1, png=>1, pnm=>1 ); # this will be SO MUCH BETTER once they are all in there
619 unless ($self->{IMG}) { $self->{ERRSTR}='empty input image'; return undef; }
621 if (!$input{file} and !$input{'fd'} and !$input{'data'}) { $self->{ERRSTR}='file/fd/data parameter missing'; return undef; }
622 if (!$input{type} and $input{file}) { $input{type}=$FORMATGUESS->($input{file}); }
623 if (!$input{type}) { $self->{ERRSTR}='type parameter missing and not possible to guess from extension'; return undef; }
625 if (!$formats{$input{type}}) { $self->{ERRSTR}='format not supported'; return undef; }
627 if (exists $input{'fd'}) {
629 } elsif (exists $input{'data'}) {
630 $IO = Imager::io_new_bufchain();
632 $fh = new IO::File($input{file},"w+");
633 if (!defined $fh) { $self->{ERRSTR}='Could not open file'; return undef; }
640 if ($iolready{$input{type}}) {
642 $IO = io_new_fd($fd);
645 if ($input{type} eq 'tiff') {
646 if (defined $input{class} && $input{class} eq 'fax') {
647 if (!i_writetiff_wiol_faxable($self->{IMG}, $IO, $input{fax_fine})) {
648 $self->{ERRSTR}='Could not write to buffer';
652 if (!i_writetiff_wiol($self->{IMG}, $IO)) {
653 $self->{ERRSTR}='Could not write to buffer';
657 } elsif ( $input{type} eq 'pnm' ) {
658 if ( ! i_writeppm_wiol($self->{IMG},$IO) ) {
659 $self->{ERRSTR}='unable to write pnm image';
662 $self->{DEBUG} && print "writing a pnm file\n";
663 } elsif ( $input{type} eq 'raw' ) {
664 if ( !i_writeraw_wiol($self->{IMG},$IO) ) {
665 $self->{ERRSTR}='unable to write raw image';
668 $self->{DEBUG} && print "writing a raw file\n";
669 } elsif ( $input{type} eq 'png' ) {
670 if ( !i_writepng_wiol($self->{IMG}, $IO) ) {
671 $self->{ERRSTR}='unable to write png image';
674 $self->{DEBUG} && print "writing a png file\n";
677 if (exists $input{'data'}) {
678 my $data = io_slurp($IO);
680 $self->{ERRSTR}='Could not slurp from buffer';
683 ${$input{data}} = $data;
688 if ( $input{type} eq 'gif' ) {
689 if (not $input{gifplanes}) {
691 my $count=i_count_colors($self->{IMG}, 256);
692 $gp=8 if $count == -1;
693 $gp=1 if not $gp and $count <= 2;
694 $gp=2 if not $gp and $count <= 4;
695 $gp=3 if not $gp and $count <= 8;
696 $gp=4 if not $gp and $count <= 16;
697 $gp=5 if not $gp and $count <= 32;
698 $gp=6 if not $gp and $count <= 64;
699 $gp=7 if not $gp and $count <= 128;
700 $input{gifplanes} = $gp || 8;
703 if ($input{gifplanes}>8) {
706 if ($input{gifquant} eq 'gen' || $input{callback}) {
709 if ($input{gifquant} eq 'lm') {
711 $input{make_colors} = 'addi';
712 $input{translate} = 'perturb';
713 $input{perturb} = $input{lmdither};
714 } elsif ($input{gifquant} eq 'gen') {
715 # just pass options through
717 $input{make_colors} = 'webmap'; # ignored
718 $input{translate} = 'giflib';
721 if ($input{callback}) {
722 defined $input{maxbuffer} or $input{maxbuffer} = -1;
723 $rc = i_writegif_callback($input{callback}, $input{maxbuffer},
724 \%input, $self->{IMG});
726 $rc = i_writegif_gen($fd, \%input, $self->{IMG});
729 } elsif ($input{gifquant} eq 'lm') {
730 $rc=i_writegif($self->{IMG},$fd,$input{gifplanes},$input{lmdither},$input{lmfixed});
732 $rc=i_writegifmc($self->{IMG},$fd,$input{gifplanes});
734 if ( !defined($rc) ) {
735 $self->{ERRSTR} = "Writing GIF file: "._error_as_msg(); return undef;
737 $self->{DEBUG} && print "writing a gif file\n";
745 my ($class, $opts, @images) = @_;
747 if ($opts->{type} eq 'gif') {
748 my $gif_delays = $opts->{gif_delays};
749 local $opts->{gif_delays} = $gif_delays;
750 unless (ref $opts->{gif_delays}) {
751 # assume the caller wants the same delay for each frame
752 $opts->{gif_delays} = [ ($gif_delays) x @images ];
754 # translate to ImgRaw
755 if (grep !UNIVERSAL::isa($_, 'Imager') || !$_->{IMG}, @images) {
756 $ERRSTR = "Usage: Imager->write_multi({ options }, @images)";
759 my @work = map $_->{IMG}, @images;
760 if ($opts->{callback}) {
761 # Note: you may need to fix giflib for this one to work
762 my $maxbuffer = $opts->{maxbuffer};
763 defined $maxbuffer or $maxbuffer = -1; # max by default
764 return i_writegif_callback($opts->{callback}, $maxbuffer,
768 return i_writegif_gen($opts->{fd}, $opts, @work);
771 my $fh = IO::File->new($opts->{file}, "w+");
773 $ERRSTR = "Error creating $opts->{file}: $!";
777 return i_writegif_gen(fileno($fh), $opts, @work);
781 $ERRSTR = "Sorry, write_multi doesn't support $opts->{type} yet";
786 # Destroy an Imager object
790 # delete $instances{$self};
791 if (defined($self->{IMG})) {
792 i_img_destroy($self->{IMG});
795 # print "Destroy Called on an empty image!\n"; # why did I put this here??
799 # Perform an inplace filter of an image
800 # that is the image will be overwritten with the data
806 unless ($self->{IMG}) { $self->{ERRSTR}='empty input image'; return undef; }
808 if (!$input{type}) { $self->{ERRSTR}='type parameter missing'; return undef; }
810 if ( (grep { $_ eq $input{type} } keys %filters) != 1) {
811 $self->{ERRSTR}='type parameter not matching any filter'; return undef;
814 if (defined($filters{$input{type}}{defaults})) {
815 %hsh=('image',$self->{IMG},%{$filters{$input{type}}{defaults}},%input);
817 %hsh=('image',$self->{IMG},%input);
820 my @cs=@{$filters{$input{type}}{callseq}};
823 if (!defined($hsh{$_})) {
824 $self->{ERRSTR}="missing parameter '$_' for filter ".$input{type}; return undef;
828 &{$filters{$input{type}}{callsub}}(%hsh);
832 $self->{DEBUG} && print "callseq is: @cs\n";
833 $self->{DEBUG} && print "matching callseq is: @b\n";
838 # Scale an image to requested size and return the scaled version
842 my %opts=(scalefactor=>0.5,type=>'max',qtype=>'normal',@_);
843 my $img = Imager->new();
844 my $tmp = Imager->new();
846 unless ($self->{IMG}) { $self->{ERRSTR}='empty input image'; return undef; }
848 if ($opts{xpixels} and $opts{ypixels} and $opts{type}) {
849 my ($xpix,$ypix)=( $opts{xpixels}/$self->getwidth() , $opts{ypixels}/$self->getheight() );
850 if ($opts{type} eq 'min') { $opts{scalefactor}=min($xpix,$ypix); }
851 if ($opts{type} eq 'max') { $opts{scalefactor}=max($xpix,$ypix); }
852 } elsif ($opts{xpixels}) { $opts{scalefactor}=$opts{xpixels}/$self->getwidth(); }
853 elsif ($opts{ypixels}) { $opts{scalefactor}=$opts{ypixels}/$self->getheight(); }
855 if ($opts{qtype} eq 'normal') {
856 $tmp->{IMG}=i_scaleaxis($self->{IMG},$opts{scalefactor},0);
857 if ( !defined($tmp->{IMG}) ) { $self->{ERRSTR}='unable to scale image'; return undef; }
858 $img->{IMG}=i_scaleaxis($tmp->{IMG},$opts{scalefactor},1);
859 if ( !defined($img->{IMG}) ) { $self->{ERRSTR}='unable to scale image'; return undef; }
862 if ($opts{'qtype'} eq 'preview') {
863 $img->{IMG}=i_scale_nn($self->{IMG},$opts{'scalefactor'},$opts{'scalefactor'});
864 if ( !defined($img->{IMG}) ) { $self->{ERRSTR}='unable to scale image'; return undef; }
867 $self->{ERRSTR}='scale: invalid value for qtype'; return undef;
870 # Scales only along the X axis
874 my %opts=(scalefactor=>0.5,@_);
876 unless ($self->{IMG}) { $self->{ERRSTR}='empty input image'; return undef; }
878 my $img = Imager->new();
880 if ($opts{pixels}) { $opts{scalefactor}=$opts{pixels}/$self->getwidth(); }
882 unless ($self->{IMG}) { $self->{ERRSTR}='empty input image'; return undef; }
883 $img->{IMG}=i_scaleaxis($self->{IMG},$opts{scalefactor},0);
885 if ( !defined($img->{IMG}) ) { $self->{ERRSTR}='unable to scale image'; return undef; }
889 # Scales only along the Y axis
893 my %opts=(scalefactor=>0.5,@_);
895 unless ($self->{IMG}) { $self->{ERRSTR}='empty input image'; return undef; }
897 my $img = Imager->new();
899 if ($opts{pixels}) { $opts{scalefactor}=$opts{pixels}/$self->getheight(); }
901 unless ($self->{IMG}) { $self->{ERRSTR}='empty input image'; return undef; }
902 $img->{IMG}=i_scaleaxis($self->{IMG},$opts{scalefactor},1);
904 if ( !defined($img->{IMG}) ) { $self->{ERRSTR}='unable to scale image'; return undef; }
909 # Transform returns a spatial transformation of the input image
910 # this moves pixels to a new location in the returned image.
911 # NOTE - should make a utility function to check transforms for
916 unless ($self->{IMG}) { $self->{ERRSTR}='empty input image'; return undef; }
918 my (@op,@ropx,@ropy,$iop,$or,@parm,$expr,@xt,@yt,@pt,$numre);
920 # print Dumper(\%opts);
923 if ( $opts{'xexpr'} and $opts{'yexpr'} ) {
925 eval ("use Affix::Infix2Postfix;");
928 $self->{ERRSTR}='transform: expr given and Affix::Infix2Postfix is not avaliable.';
931 $I2P=Affix::Infix2Postfix->new('ops'=>[{op=>'+',trans=>'Add'},
932 {op=>'-',trans=>'Sub'},
933 {op=>'*',trans=>'Mult'},
934 {op=>'/',trans=>'Div'},
935 {op=>'-',type=>'unary',trans=>'u-'},
937 {op=>'func',type=>'unary'}],
938 'grouping'=>[qw( \( \) )],
939 'func'=>[qw( sin cos )],
944 @xt=$I2P->translate($opts{'xexpr'});
945 @yt=$I2P->translate($opts{'yexpr'});
947 $numre=$I2P->{'numre'};
950 for(@xt) { if (/$numre/) { push(@pt,$_); push(@{$opts{'xopcodes'}},'Parm',$#pt); } else { push(@{$opts{'xopcodes'}},$_); } }
951 for(@yt) { if (/$numre/) { push(@pt,$_); push(@{$opts{'yopcodes'}},'Parm',$#pt); } else { push(@{$opts{'yopcodes'}},$_); } }
952 @{$opts{'parm'}}=@pt;
955 # print Dumper(\%opts);
957 if ( !exists $opts{'xopcodes'} or @{$opts{'xopcodes'}}==0) {
958 $self->{ERRSTR}='transform: no xopcodes given.';
962 @op=@{$opts{'xopcodes'}};
964 if (!defined ($OPCODES{$iop}) and ($iop !~ /^\d+$/) ) {
965 $self->{ERRSTR}="transform: illegal opcode '$_'.";
968 push(@ropx,(exists $OPCODES{$iop}) ? @{$OPCODES{$iop}} : $iop );
974 if ( !exists $opts{'yopcodes'} or @{$opts{'yopcodes'}}==0) {
975 $self->{ERRSTR}='transform: no yopcodes given.';
979 @op=@{$opts{'yopcodes'}};
981 if (!defined ($OPCODES{$iop}) and ($iop !~ /^\d+$/) ) {
982 $self->{ERRSTR}="transform: illegal opcode '$_'.";
985 push(@ropy,(exists $OPCODES{$iop}) ? @{$OPCODES{$iop}} : $iop );
990 if ( !exists $opts{'parm'}) {
991 $self->{ERRSTR}='transform: no parameter arg given.';
995 # print Dumper(\@ropx);
996 # print Dumper(\@ropy);
997 # print Dumper(\@ropy);
999 my $img = Imager->new();
1000 $img->{IMG}=i_transform($self->{IMG},\@ropx,\@ropy,$opts{'parm'});
1001 if ( !defined($img->{IMG}) ) { $self->{ERRSTR}='transform: failed'; return undef; }
1009 my ($opts, @imgs) = @_;
1012 # this is fairly big, delay loading it
1013 eval "use Imager::Expr";
1018 $opts->{variables} = [ qw(x y) ];
1019 my ($width, $height) = @{$opts}{qw(width height)};
1021 $width ||= $imgs[0]->getwidth();
1022 $height ||= $imgs[0]->getheight();
1024 for my $img (@imgs) {
1025 $opts->{constants}{"w$img_num"} = $img->getwidth();
1026 $opts->{constants}{"h$img_num"} = $img->getheight();
1027 $opts->{constants}{"cx$img_num"} = $img->getwidth()/2;
1028 $opts->{constants}{"cy$img_num"} = $img->getheight()/2;
1033 $opts->{constants}{w} = $width;
1034 $opts->{constants}{cx} = $width/2;
1037 $Imager::ERRSTR = "No width supplied";
1041 $opts->{constants}{h} = $height;
1042 $opts->{constants}{cy} = $height/2;
1045 $Imager::ERRSTR = "No height supplied";
1048 my $code = Imager::Expr->new($opts);
1050 $Imager::ERRSTR = Imager::Expr::error();
1054 my $img = Imager->new();
1055 $img->{IMG} = i_transform2($opts->{width}, $opts->{height}, $code->code(),
1056 $code->nregs(), $code->cregs(),
1057 [ map { $_->{IMG} } @imgs ]);
1058 if (!defined $img->{IMG}) {
1059 $Imager::ERRSTR = "transform2 failed";
1076 my %opts=(tx=>0,ty=>0,@_);
1078 unless ($self->{IMG}) { $self->{ERRSTR}='empty input image'; return undef; }
1079 unless ($opts{src} && $opts{src}->{IMG}) { $self->{ERRSTR}='empty input image for source'; return undef; }
1081 i_rubthru($self->{IMG}, $opts{src}->{IMG}, $opts{tx},$opts{ty});
1089 my %xlate = (h=>0, v=>1, hv=>2, vh=>2);
1091 return () unless defined $opts{'dir'} and defined $xlate{$opts{'dir'}};
1092 $dir = $xlate{$opts{'dir'}};
1093 return $self if i_flipxy($self->{IMG}, $dir);
1099 # These two are supported for legacy code only
1102 return Imager::Color->new($_[0], $_[1], $_[2], $_[3]);
1106 return Imager::Color::set($_[0], $_[1], $_[2], $_[3], $_[4]);
1111 # Draws a box between the specified corner points.
1115 unless ($self->{IMG}) { $self->{ERRSTR}='empty input image'; return undef; }
1116 my $dflcl=i_color_new(255,255,255,255);
1117 my %opts=(color=>$dflcl,xmin=>0,ymin=>0,xmax=>$self->getwidth()-1,ymax=>$self->getheight()-1,@_);
1119 if (exists $opts{'box'}) {
1120 $opts{'xmin'} = min($opts{'box'}->[0],$opts{'box'}->[2]);
1121 $opts{'xmax'} = max($opts{'box'}->[0],$opts{'box'}->[2]);
1122 $opts{'ymin'} = min($opts{'box'}->[1],$opts{'box'}->[3]);
1123 $opts{'ymax'} = max($opts{'box'}->[1],$opts{'box'}->[3]);
1126 if ($opts{filled}) { i_box_filled($self->{IMG},$opts{xmin},$opts{ymin},$opts{xmax},$opts{ymax},$opts{color}); }
1127 else { i_box($self->{IMG},$opts{xmin},$opts{ymin},$opts{xmax},$opts{ymax},$opts{color}); }
1131 # Draws an arc - this routine SUCKS and is buggy - it sometimes doesn't work when the arc is a convex polygon
1135 unless ($self->{IMG}) { $self->{ERRSTR}='empty input image'; return undef; }
1136 my $dflcl=i_color_new(255,255,255,255);
1137 my %opts=(color=>$dflcl,
1138 'r'=>min($self->getwidth(),$self->getheight())/3,
1139 'x'=>$self->getwidth()/2,
1140 'y'=>$self->getheight()/2,
1141 'd1'=>0, 'd2'=>361, @_);
1142 i_arc($self->{IMG},$opts{'x'},$opts{'y'},$opts{'r'},$opts{'d1'},$opts{'d2'},$opts{'color'});
1146 # Draws a line from one point to (but not including) the destination point
1150 my $dflcl=i_color_new(0,0,0,0);
1151 my %opts=(color=>$dflcl,@_);
1152 unless ($self->{IMG}) { $self->{ERRSTR}='empty input image'; return undef; }
1154 unless (exists $opts{x1} and exists $opts{y1}) { $self->{ERRSTR}='missing begining coord'; return undef; }
1155 unless (exists $opts{x2} and exists $opts{y2}) { $self->{ERRSTR}='missing ending coord'; return undef; }
1157 if ($opts{antialias}) {
1158 i_line_aa($self->{IMG},$opts{x1}, $opts{y1}, $opts{x2}, $opts{y2}, $opts{color});
1160 i_draw($self->{IMG},$opts{x1}, $opts{y1}, $opts{x2}, $opts{y2}, $opts{color});
1165 # Draws a line between an ordered set of points - It more or less just transforms this
1166 # into a list of lines.
1170 my ($pt,$ls,@points);
1171 my $dflcl=i_color_new(0,0,0,0);
1172 my %opts=(color=>$dflcl,@_);
1174 unless ($self->{IMG}) { $self->{ERRSTR}='empty input image'; return undef; }
1176 if (exists($opts{points})) { @points=@{$opts{points}}; }
1177 if (!exists($opts{points}) and exists($opts{'x'}) and exists($opts{'y'}) ) {
1178 @points=map { [ $opts{'x'}->[$_],$opts{'y'}->[$_] ] } (0..(scalar @{$opts{'x'}}-1));
1181 # print Dumper(\@points);
1183 if ($opts{antialias}) {
1185 if (defined($ls)) { i_line_aa($self->{IMG},$ls->[0],$ls->[1],$pt->[0],$pt->[1],$opts{color}); }
1190 if (defined($ls)) { i_draw($self->{IMG},$ls->[0],$ls->[1],$pt->[0],$pt->[1],$opts{color}); }
1197 # this the multipoint bezier curve
1198 # this is here more for testing that actual usage since
1199 # this is not a good algorithm. Usually the curve would be
1200 # broken into smaller segments and each done individually.
1204 my ($pt,$ls,@points);
1205 my $dflcl=i_color_new(0,0,0,0);
1206 my %opts=(color=>$dflcl,@_);
1208 unless ($self->{IMG}) { $self->{ERRSTR}='empty input image'; return undef; }
1210 if (exists $opts{points}) {
1211 $opts{'x'}=map { $_->[0]; } @{$opts{'points'}};
1212 $opts{'y'}=map { $_->[1]; } @{$opts{'points'}};
1215 unless ( @{$opts{'x'}} and @{$opts{'x'}} == @{$opts{'y'}} ) {
1216 $self->{ERRSTR}='Missing or invalid points.';
1220 i_bezier_multi($self->{IMG},$opts{'x'},$opts{'y'},$opts{'color'});
1224 # make an identity matrix of the given size
1228 my $matrix = [ map { [ (0) x $size ] } 1..$size ];
1229 for my $c (0 .. ($size-1)) {
1230 $matrix->[$c][$c] = 1;
1235 # general function to convert an image
1237 my ($self, %opts) = @_;
1240 # the user can either specify a matrix or preset
1241 # the matrix overrides the preset
1242 if (!exists($opts{matrix})) {
1243 unless (exists($opts{preset})) {
1244 $self->{ERRSTR} = "convert() needs a matrix or preset";
1248 if ($opts{preset} eq 'gray' || $opts{preset} eq 'grey') {
1249 # convert to greyscale, keeping the alpha channel if any
1250 if ($self->getchannels == 3) {
1251 $matrix = [ [ 0.222, 0.707, 0.071 ] ];
1253 elsif ($self->getchannels == 4) {
1254 # preserve the alpha channel
1255 $matrix = [ [ 0.222, 0.707, 0.071, 0 ],
1260 $matrix = _identity($self->getchannels);
1263 elsif ($opts{preset} eq 'noalpha') {
1264 # strip the alpha channel
1265 if ($self->getchannels == 2 or $self->getchannels == 4) {
1266 $matrix = _identity($self->getchannels);
1267 pop(@$matrix); # lose the alpha entry
1270 $matrix = _identity($self->getchannels);
1273 elsif ($opts{preset} eq 'red' || $opts{preset} eq 'channel0') {
1275 $matrix = [ [ 1 ] ];
1277 elsif ($opts{preset} eq 'green' || $opts{preset} eq 'channel1') {
1278 $matrix = [ [ 0, 1 ] ];
1280 elsif ($opts{preset} eq 'blue' || $opts{preset} eq 'channel2') {
1281 $matrix = [ [ 0, 0, 1 ] ];
1283 elsif ($opts{preset} eq 'alpha') {
1284 if ($self->getchannels == 2 or $self->getchannels == 4) {
1285 $matrix = [ [ (0) x ($self->getchannels-1), 1 ] ];
1288 # the alpha is just 1 <shrug>
1289 $matrix = [ [ (0) x $self->getchannels, 1 ] ];
1292 elsif ($opts{preset} eq 'rgb') {
1293 if ($self->getchannels == 1) {
1294 $matrix = [ [ 1 ], [ 1 ], [ 1 ] ];
1296 elsif ($self->getchannels == 2) {
1297 # preserve the alpha channel
1298 $matrix = [ [ 1, 0 ], [ 1, 0 ], [ 1, 0 ], [ 0, 1 ] ];
1301 $matrix = _identity($self->getchannels);
1304 elsif ($opts{preset} eq 'addalpha') {
1305 if ($self->getchannels == 1) {
1306 $matrix = _identity(2);
1308 elsif ($self->getchannels == 3) {
1309 $matrix = _identity(4);
1312 $matrix = _identity($self->getchannels);
1316 $self->{ERRSTR} = "Unknown convert preset $opts{preset}";
1322 $matrix = $opts{matrix};
1325 my $new = Imager->new();
1326 $new->{IMG} = i_img_new();
1327 unless (i_convert($new->{IMG}, $self->{IMG}, $matrix)) {
1328 # most likely a bad matrix
1329 $self->{ERRSTR} = _error_as_msg();
1336 # general function to map an image through lookup tables
1339 my ($self, %opts) = @_;
1340 my @chlist = qw( red green blue alpha );
1342 if (!exists($opts{'maps'})) {
1343 # make maps from channel maps
1345 for $chnum (0..$#chlist) {
1346 if (exists $opts{$chlist[$chnum]}) {
1347 $opts{'maps'}[$chnum] = $opts{$chlist[$chnum]};
1348 } elsif (exists $opts{'all'}) {
1349 $opts{'maps'}[$chnum] = $opts{'all'};
1353 if ($opts{'maps'} and $self->{IMG}) {
1354 i_map($self->{IMG}, $opts{'maps'} );
1370 # destructive border - image is shrunk by one pixel all around
1373 my ($self,%opts)=@_;
1374 my($tx,$ty)=($self->getwidth()-1,$self->getheight()-1);
1375 $self->polyline('x'=>[0,$tx,$tx,0,0],'y'=>[0,0,$ty,$ty,0],%opts);
1379 # Get the width of an image
1383 if (!defined($self->{IMG})) { $self->{ERRSTR} = 'image is empty'; return undef; }
1384 return (i_img_info($self->{IMG}))[0];
1387 # Get the height of an image
1391 if (!defined($self->{IMG})) { $self->{ERRSTR} = 'image is empty'; return undef; }
1392 return (i_img_info($self->{IMG}))[1];
1395 # Get number of channels in an image
1399 if (!defined($self->{IMG})) { $self->{ERRSTR} = 'image is empty'; return undef; }
1400 return i_img_getchannels($self->{IMG});
1407 if (!defined($self->{IMG})) { $self->{ERRSTR} = 'image is empty'; return undef; }
1408 return i_img_getmask($self->{IMG});
1416 if (!defined($self->{IMG})) { $self->{ERRSTR} = 'image is empty'; return undef; }
1417 i_img_setmask( $self->{IMG} , $opts{mask} );
1420 # Get number of colors in an image
1424 my %opts=(maxcolors=>2**30,@_);
1425 if (!defined($self->{IMG})) { $self->{ERRSTR}='image is empty'; return undef; }
1426 my $rc=i_count_colors($self->{IMG},$opts{'maxcolors'});
1427 return ($rc==-1? undef : $rc);
1430 # draw string to an image
1434 unless ($self->{IMG}) { $self->{ERRSTR}='empty input image'; return undef; }
1436 my %input=('x'=>0, 'y'=>0, @_);
1437 $input{string}||=$input{text};
1439 unless(exists $input{string}) {
1440 $self->{ERRSTR}="missing required parameter 'string'";
1444 unless($input{font}) {
1445 $self->{ERRSTR}="missing required parameter 'font'";
1449 $input{font}->draw(image=>$self, %input);
1458 # Shortcuts that can be exported
1460 sub newcolor { Imager::Color->new(@_); }
1461 sub newfont { Imager::Font->new(@_); }
1463 *NC=*newcolour=*newcolor;
1470 #### Utility routines
1472 sub errstr { $_[0]->{ERRSTR} }
1479 # Default guess for the type of an image from extension
1481 sub def_guess_type {
1484 $ext=($name =~ m/\.([^\.]+)$/)[0];
1485 return 'tiff' if ($ext =~ m/^tiff?$/);
1486 return 'jpeg' if ($ext =~ m/^jpe?g$/);
1487 return 'pnm' if ($ext =~ m/^p[pgb]m$/);
1488 return 'png' if ($ext eq "png");
1489 return 'gif' if ($ext eq "gif");
1493 # get the minimum of a list
1497 for(@_) { if ($_<$mx) { $mx=$_; }}
1501 # get the maximum of a list
1505 for(@_) { if ($_>$mx) { $mx=$_; }}
1509 # string stuff for iptc headers
1513 $str = substr($str,3);
1514 $str =~ s/[\n\r]//g;
1521 # A little hack to parse iptc headers.
1526 my($caption,$photogr,$headln,$credit);
1528 my $str=$self->{IPTCRAW};
1532 @ar=split(/8BIM/,$str);
1537 @sar=split(/\034\002/);
1538 foreach $item (@sar) {
1539 if ($item =~ m/^x/) {
1540 $caption=&clean($item);
1543 if ($item =~ m/^P/) {
1544 $photogr=&clean($item);
1547 if ($item =~ m/^i/) {
1548 $headln=&clean($item);
1551 if ($item =~ m/^n/) {
1552 $credit=&clean($item);
1558 return (caption=>$caption,photogr=>$photogr,headln=>$headln,credit=>$credit);
1566 # Autoload methods go after =cut, and are processed by the autosplit program.
1570 # Below is the stub of documentation for your module. You better edit it!
1574 Imager - Perl extension for Generating 24 bit Images
1578 use Imager qw(init);
1581 $img = Imager->new();
1582 $img->open(file=>'image.ppm',type=>'pnm')
1583 || print "failed: ",$img->{ERRSTR},"\n";
1584 $scaled=$img->scale(xpixels=>400,ypixels=>400);
1585 $scaled->write(file=>'sc_image.ppm',type=>'pnm')
1586 || print "failed: ",$scaled->{ERRSTR},"\n";
1590 Imager is a module for creating and altering images - It is not meant
1591 as a replacement or a competitor to ImageMagick or GD. Both are
1592 excellent packages and well supported.
1596 Almost all functions take the parameters in the hash fashion.
1599 $img->open(file=>'lena.png',type=>'png');
1603 $img->open(file=>'lena.png');
1605 =head2 Basic concept
1607 An Image object is created with C<$img = Imager-E<gt>new()> Should
1608 this fail for some reason an explanation can be found in
1609 C<$Imager::ERRSTR> usually error messages are stored in
1610 C<$img-E<gt>{ERRSTR}>, but since no object is created this is the only
1611 way to give back errors. C<$Imager::ERRSTR> is also used to report
1612 all errors not directly associated with an image object. Examples:
1614 $img=Imager->new(); # This is an empty image (size is 0 by 0)
1615 $img->open(file=>'lena.png',type=>'png'); # initializes from file
1617 or if you want to create an empty image:
1619 $img=Imager->new(xsize=>400,ysize=>300,channels=>4);
1621 This example creates a completely black image of width 400 and
1622 height 300 and 4 channels.
1624 If you have an existing image, use img_set() to change it's dimensions
1625 - this will destroy any existing image data:
1627 $img->img_set(xsize=>500, ysize=>500, channels=>4);
1629 Color objects are created by calling the Imager::Color->new()
1632 $color = Imager::Color->new($red, $green, $blue);
1633 $color = Imager::Color->new($red, $green, $blue, $alpha);
1634 $color = Imager::Color->new("#C0C0FF"); # html color specification
1636 This object can then be passed to functions that require a color parameter.
1638 Coordinates in Imager have the origin in the upper left corner. The
1639 horizontal coordinate increases to the right and the vertical
1642 =head2 Reading and writing images
1644 C<$img-E<gt>read()> generally takes two parameters, 'file' and 'type'.
1645 If the type of the file can be determined from the suffix of the file
1646 it can be omitted. Format dependant parameters are: For images of
1647 type 'raw' two extra parameters are needed 'xsize' and 'ysize', if the
1648 'channel' parameter is omitted for type 'raw' it is assumed to be 3.
1649 gif and png images might have a palette are converted to truecolor bit
1650 when read. Alpha channel is preserved for png images irregardless of
1651 them being in RGB or gray colorspace. Similarly grayscale jpegs are
1652 one channel images after reading them. For jpeg images the iptc
1653 header information (stored in the APP13 header) is avaliable to some
1654 degree. You can get the raw header with C<$img-E<gt>{IPTCRAW}>, but
1655 you can also retrieve the most basic information with
1656 C<%hsh=$img-E<gt>parseiptc()> as always patches are welcome. pnm has no
1657 extra options. Examples:
1659 $img = Imager->new();
1660 $img->read(file=>"cover.jpg") or die $img->errstr; # gets type from name
1662 $img = Imager->new();
1663 { local(*FH,$/); open(FH,"file.gif") or die $!; $a=<FH>; }
1664 $img->read(data=>$a,type=>'gif') or die $img->errstr;
1666 The second example shows how to read an image from a scalar, this is
1667 usefull if your data originates from somewhere else than a filesystem
1668 such as a database over a DBI connection.
1670 When writing to a tiff image file you can also specify the 'class'
1671 parameter, which can currently take a single value, "fax". If class
1672 is set to fax then a tiff image which should be suitable for faxing
1673 will be written. For the best results start with a grayscale image.
1674 By default the image is written at fine resolution you can override
1675 this by setting the "fax_fine" parameter to 0.
1677 If you are reading from a gif image file, you can supply a 'colors'
1678 parameter which must be a reference to a scalar. The referenced
1679 scalar will receive an array reference which contains the colors, each
1680 represented as an Imager::Color object.
1682 If you already have an open file handle, for example a socket or a
1683 pipe, you can specify the 'fd' parameter instead of supplying a
1684 filename. Please be aware that you need to use fileno() to retrieve
1685 the file descriptor for the file:
1687 $img->read(fd=>fileno(FILE), type=>'gif') or die $img->errstr;
1689 For writing using the 'fd' option you will probably want to set $| for
1690 that descriptor, since the writes to the file descriptor bypass Perl's
1691 (or the C libraries) buffering. Setting $| should avoid out of order
1694 *Note that load() is now an alias for read but will be removed later*
1696 C<$img-E<gt>write> has the same interface as C<read()>. The earlier
1697 comments on C<read()> for autodetecting filetypes apply. For jpegs
1698 quality can be adjusted via the 'jpegquality' parameter (0-100). The
1699 number of colorplanes in gifs are set with 'gifplanes' and should be
1700 between 1 (2 color) and 8 (256 colors). It is also possible to choose
1701 between two quantizing methods with the parameter 'gifquant'. If set
1702 to mc it uses the mediancut algorithm from either giflibrary. If set
1703 to lm it uses a local means algorithm. It is then possible to give
1704 some extra settings. lmdither is the dither deviation amount in pixels
1705 (manhattan distance). lmfixed can be an array ref who holds an array
1706 of Imager::Color objects. Note that the local means algorithm needs
1707 much more cpu time but also gives considerable better results than the
1708 median cut algorithm.
1710 Currently just for gif files, you can specify various options for the
1711 conversion from Imager's internal RGB format to the target's indexed
1712 file format. If you set the gifquant option to 'gen', you can use the
1713 options specified under L<Quantization options>.
1715 To see what Imager is compiled to support the following code snippet
1719 print "@{[keys %Imager::formats]}";
1721 When reading raw images you need to supply the width and height of the
1722 image in the xsize and ysize options:
1724 $img->read(file=>'foo.raw', xsize=>100, ysize=>100)
1725 or die "Cannot read raw image\n";
1727 If your input file has more channels than you want, or (as is common),
1728 junk in the fourth channel, you can use the datachannels and
1729 storechannels options to control the number of channels in your input
1730 file and the resulting channels in your image. For example, if your
1731 input image uses 32-bits per pixel with red, green, blue and junk
1732 values for each pixel you could do:
1734 $img->read(file=>'foo.raw', xsize=>100, ysize=>100, datachannels=>4,
1736 or die "Cannot read raw image\n";
1738 Normally the raw image is expected to have the value for channel 1
1739 immediately following channel 0 and channel 2 immediately following
1740 channel 1 for each pixel. If your input image has all the channel 0
1741 values for the first line of the image, followed by all the channel 1
1742 values for the first line and so on, you can use the interleave option:
1744 $img->read(file=>'foo.raw', xsize=100, ysize=>100, interleave=>1)
1745 or die "Cannot read raw image\n";
1747 =head2 Multi-image files
1749 Currently just for gif files, you can create files that contain more
1754 Imager->write_multi(\%opts, @images)
1756 Where %opts describes 4 possible types of outputs:
1762 This is C<gif> for gif animations.
1766 A code reference which is called with a single parameter, the data to
1767 be written. You can also specify $opts{maxbuffer} which is the
1768 maximum amount of data buffered. Note that there can be larger writes
1769 than this if the file library writes larger blocks. A smaller value
1770 maybe useful for writing to a socket for incremental display.
1774 The file descriptor to save the images to.
1778 The name of the file to write to.
1780 %opts may also include the keys from L<Gif options> and L<Quantization
1785 You must also specify the file format using the 'type' option.
1787 The current aim is to support other multiple image formats in the
1788 future, such as TIFF, and to support reading multiple images from a
1794 # ... code to put images in @images
1795 Imager->write_multi({type=>'gif',
1797 gif_delays=>[ (10) x @images ] },
1803 These options can be specified when calling write_multi() for gif
1804 files, when writing a single image with the gifquant option set to
1805 'gen', or for direct calls to i_writegif_gen and i_writegif_callback.
1807 Note that some viewers will ignore some of these options
1808 (gif_user_input in particular).
1812 =item gif_each_palette
1814 Each image in the gif file has it's own palette if this is non-zero.
1815 All but the first image has a local colour table (the first uses the
1816 global colour table.
1820 The images are written interlaced if this is non-zero.
1824 A reference to an array containing the delays between images, in 1/100
1827 If you want the same delay for every frame you can simply set this to
1828 the delay in 1/100 seconds.
1830 =item gif_user_input
1832 A reference to an array contains user input flags. If the given flag
1833 is non-zero the image viewer should wait for input before displaying
1838 A reference to an array of image disposal methods. These define what
1839 should be done to the image before displaying the next one. These are
1840 integers, where 0 means unspecified, 1 means the image should be left
1841 in place, 2 means restore to background colour and 3 means restore to
1844 =item gif_tran_color
1846 A reference to an Imager::Color object, which is the colour to use for
1847 the palette entry used to represent transparency in the palette. You
1848 need to set the transp option (see L<Quantization options>) for this
1853 A reference to an array of references to arrays which represent screen
1854 positions for each image.
1856 =item gif_loop_count
1858 If this is non-zero the Netscape loop extension block is generated,
1859 which makes the animation of the images repeat.
1861 This is currently unimplemented due to some limitations in giflib.
1865 =head2 Quantization options
1867 These options can be specified when calling write_multi() for gif
1868 files, when writing a single image with the gifquant option set to
1869 'gen', or for direct calls to i_writegif_gen and i_writegif_callback.
1875 A arrayref of colors that are fixed. Note that some color generators
1880 The type of transparency processing to perform for images with an
1881 alpha channel where the output format does not have a proper alpha
1882 channel (eg. gif). This can be any of:
1888 No transparency processing is done. (default)
1892 Pixels more transparent that tr_threshold are rendered as transparent.
1896 An error diffusion dither is done on the alpha channel. Note that
1897 this is independent of the translation performed on the colour
1898 channels, so some combinations may cause undesired artifacts.
1902 The ordered dither specified by tr_orddith is performed on the alpha
1907 This will only be used if the image has an alpha channel, and if there
1908 is space in the palette for a transparency colour.
1912 The highest alpha value at which a pixel will be made transparent when
1913 transp is 'threshold'. (0-255, default 127)
1917 The type of error diffusion to perform on the alpha channel when
1918 transp is 'errdiff'. This can be any defined error diffusion type
1919 except for custom (see errdiff below).
1923 The type of ordered dither to perform on the alpha channel when transp
1924 is 'ordered'. Possible values are:
1930 A semi-random map is used. The map is the same each time.
1942 horizontal line dither.
1946 vertical line dither.
1952 diagonal line dither
1958 diagonal line dither
1962 dot matrix dither (currently the default). This is probably the best
1963 for displays (like web pages).
1967 A custom dither matrix is used - see tr_map
1973 When tr_orddith is custom this defines an 8 x 8 matrix of integers
1974 representing the transparency threshold for pixels corresponding to
1975 each position. This should be a 64 element array where the first 8
1976 entries correspond to the first row of the matrix. Values should be
1981 Defines how the quantization engine will build the palette(s).
1982 Currently this is ignored if 'translate' is 'giflib', but that may
1983 change. Possible values are:
1989 Only colors supplied in 'colors' are used.
1993 The web color map is used (need url here.)
1997 The original code for generating the color map (Addi's code) is used.
2001 Other methods may be added in the future.
2005 A arrayref containing Imager::Color objects, which represents the
2006 starting set of colors to use in translating the images. webmap will
2007 ignore this. The final colors used are copied back into this array
2008 (which is expanded if necessary.)
2012 The maximum number of colors to use in the image.
2016 The method used to translate the RGB values in the source image into
2017 the colors selected by make_colors. Note that make_colors is ignored
2018 whene translate is 'giflib'.
2020 Possible values are:
2026 The giflib native quantization function is used.
2030 The closest color available is used.
2034 The pixel color is modified by perturb, and the closest color is chosen.
2038 An error diffusion dither is performed.
2042 It's possible other transate values will be added.
2046 The type of error diffusion dither to perform. These values (except
2047 for custom) can also be used in tr_errdif.
2053 Floyd-Steinberg dither
2057 Jarvis, Judice and Ninke dither
2065 Custom. If you use this you must also set errdiff_width,
2066 errdiff_height and errdiff_map.
2072 =item errdiff_height
2078 When translate is 'errdiff' and errdiff is 'custom' these define a
2079 custom error diffusion map. errdiff_width and errdiff_height define
2080 the size of the map in the arrayref in errdiff_map. errdiff_orig is
2081 an integer which indicates the current pixel position in the top row
2086 When translate is 'perturb' this is the magnitude of the random bias
2087 applied to each channel of the pixel before it is looked up in the
2092 =head2 Obtaining/setting attributes of images
2094 To get the size of an image in pixels the C<$img-E<gt>getwidth()> and
2095 C<$img-E<gt>getheight()> are used.
2097 To get the number of channels in
2098 an image C<$img-E<gt>getchannels()> is used. $img-E<gt>getmask() and
2099 $img-E<gt>setmask() are used to get/set the channel mask of the image.
2101 $mask=$img->getmask();
2102 $img->setmask(mask=>1+2); # modify red and green only
2103 $img->setmask(mask=>8); # modify alpha only
2104 $img->setmask(mask=>$mask); # restore previous mask
2106 The mask of an image describes which channels are updated when some
2107 operation is performed on an image. Naturally it is not possible to
2108 apply masks to operations like scaling that alter the dimensions of
2111 It is possible to have Imager find the number of colors in an image
2112 by using C<$img-E<gt>getcolorcount()>. It requires memory proportionally
2113 to the number of colors in the image so it is possible to have it
2114 stop sooner if you only need to know if there are more than a certain number
2115 of colors in the image. If there are more colors than asked for
2116 the function return undef. Examples:
2118 if (!defined($img->getcolorcount(maxcolors=>512)) {
2119 print "Less than 512 colors in image\n";
2122 =head2 Drawing Methods
2124 IMPLEMENTATION MORE OR LESS DONE CHECK THE TESTS
2125 DOCUMENTATION OF THIS SECTION OUT OF SYNC
2127 It is possible to draw with graphics primitives onto images. Such
2128 primitives include boxes, arcs, circles and lines. A reference
2129 oriented list follows.
2132 $img->box(color=>$blue,xmin=>10,ymin=>30,xmax=>200,ymax=>300,filled=>1);
2134 The above example calls the C<box> method for the image and the box
2135 covers the pixels with in the rectangle specified. If C<filled> is
2136 ommited it is drawn as an outline. If any of the edges of the box are
2137 ommited it will snap to the outer edge of the image in that direction.
2138 Also if a color is omitted a color with (255,255,255,255) is used
2142 $img->arc(color=>$red, r=20, x=>200, y=>100, d1=>10, d2=>20 );
2144 This creates a filled red arc with a 'center' at (200, 100) and spans
2145 10 degrees and the slice has a radius of 20. SEE section on BUGS.
2148 $img->circle(color=>$green, r=50, x=>200, y=>100);
2150 This creates a green circle with its center at (200, 100) and has a
2154 $img->line(color=>$green, x1=10, x2=>100,
2155 y1=>20, y2=>50, antialias=>1 );
2157 That draws an antialiased line from (10,100) to (20,50).
2160 $img->polyline(points=>[[$x0,$y0],[$x1,$y1],[$x2,$y2]],color=>$red);
2161 $img->polyline(x=>[$x0,$x1,$x2], y=>[$y0,$y1,$y2], antialias=>1);
2163 Polyline is used to draw multilple lines between a series of points.
2164 The point set can either be specified as an arrayref to an array of
2165 array references (where each such array represents a point). The
2166 other way is to specify two array references.
2168 =head2 Text rendering
2170 Text rendering is described in the Imager::Font manpage.
2172 =head2 Image resizing
2174 To scale an image so porportions are maintained use the
2175 C<$img-E<gt>scale()> method. if you give either a xpixels or ypixels
2176 parameter they will determine the width or height respectively. If
2177 both are given the one resulting in a larger image is used. example:
2178 C<$img> is 700 pixels wide and 500 pixels tall.
2180 $img->scale(xpixels=>400); # 400x285
2181 $img->scale(ypixels=>400); # 560x400
2183 $img->scale(xpixels=>400,ypixels=>400); # 560x400
2184 $img->scale(xpixels=>400,ypixels=>400,type=>min); # 400x285
2186 $img->scale(scalefactor=>0.25); 175x125 $img->scale(); # 350x250
2188 if you want to create low quality previews of images you can pass
2189 C<qtype=E<gt>'preview'> to scale and it will use nearest neighbor
2190 sampling instead of filtering. It is much faster but also generates
2191 worse looking images - especially if the original has a lot of sharp
2192 variations and the scaled image is by more than 3-5 times smaller than
2195 If you need to scale images per axis it is best to do it simply by
2196 calling scaleX and scaleY. You can pass either 'scalefactor' or
2197 'pixels' to both functions.
2199 Another way to resize an image size is to crop it. The parameters
2200 to crop are the edges of the area that you want in the returned image.
2201 If a parameter is omited a default is used instead.
2203 $newimg = $img->crop(left=>50, right=>100, top=>10, bottom=>100);
2204 $newimg = $img->crop(left=>50, top=>10, width=>50, height=>90);
2205 $newimg = $img->crop(left=>50, right=>100); # top
2207 You can also specify width and height parameters which will produce a
2208 new image cropped from the center of the input image, with the given
2211 $newimg = $img->crop(width=>50, height=>50);
2213 The width and height parameters take precedence over the left/right
2214 and top/bottom parameters respectively.
2216 =head2 Copying images
2218 To create a copy of an image use the C<copy()> method. This is usefull
2219 if you want to keep an original after doing something that changes the image
2220 inplace like writing text.
2224 To copy an image to onto another image use the C<paste()> method.
2226 $dest->paste(left=>40,top=>20,img=>$logo);
2228 That copies the entire C<$logo> image onto the C<$dest> image so that the
2229 upper left corner of the C<$logo> image is at (40,20).
2232 =head2 Flipping images
2234 An inplace horizontal or vertical flip is possible by calling the
2235 C<flip()> method. If the original is to be preserved it's possible to
2236 make a copy first. The only parameter it takes is the C<dir>
2237 parameter which can take the values C<h>, C<v>, C<vh> and C<hv>.
2239 $img->flip(dir=>"h"); # horizontal flip
2240 $img->flip(dir=>"vh"); # vertical and horizontal flip
2241 $nimg = $img->copy->flip(dir=>"v"); # make a copy and flip it vertically
2243 =head2 Blending Images
2245 To put an image or a part of an image directly
2246 into another it is best to call the C<paste()> method on the image you
2249 $img->paste(img=>$srcimage,left=>30,top=>50);
2251 That will take paste C<$srcimage> into C<$img> with the upper
2252 left corner at (30,50). If no values are given for C<left>
2253 or C<top> they will default to 0.
2255 A more complicated way of blending images is where one image is
2256 put 'over' the other with a certain amount of opaqueness. The
2257 method that does this is rubthrough.
2259 $img->rubthrough(src=>$srcimage,tx=>30,ty=>50);
2261 That will take the image C<$srcimage> and overlay it with the
2262 upper left corner at (30,50). The C<$srcimage> must be a 4 channel
2263 image. The last channel is used as an alpha channel.
2268 A special image method is the filter method. An example is:
2270 $img->filter(type=>'autolevels');
2272 This will call the autolevels filter. Here is a list of the filters
2273 that are always avaliable in Imager. This list can be obtained by
2274 running the C<filterlist.perl> script that comes with the module
2279 autolevels lsat(0.1) usat(0.1) skew(0)
2281 noise amount(3) subtype(0)
2284 gradgen xo yo colors dist
2286 The default values are in parenthesis. All parameters must have some
2287 value but if a parameter has a default value it may be omitted when
2288 calling the filter function.
2290 FIXME: make a seperate pod for filters?
2292 =head2 Color transformations
2294 You can use the convert method to transform the color space of an
2295 image using a matrix. For ease of use some presets are provided.
2297 The convert method can be used to:
2303 convert an RGB or RGBA image to grayscale.
2307 convert a grayscale image to RGB.
2311 extract a single channel from an image.
2315 set a given channel to a particular value (or from another channel)
2319 The currently defined presets are:
2327 converts an RGBA image into a grayscale image with alpha channel, or
2328 an RGB image into a grayscale image without an alpha channel.
2330 This weights the RGB channels at 22.2%, 70.7% and 7.1% respectively.
2334 removes the alpha channel from a 2 or 4 channel image. An identity
2341 extracts the first channel of the image into a single channel image
2347 extracts the second channel of the image into a single channel image
2353 extracts the third channel of the image into a single channel image
2357 extracts the alpha channel of the image into a single channel image.
2359 If the image has 1 or 3 channels (assumed to be grayscale of RGB) then
2360 the resulting image will be all white.
2364 converts a grayscale image to RGB, preserving the alpha channel if any
2368 adds an alpha channel to a grayscale or RGB image. Preserves an
2369 existing alpha channel for a 2 or 4 channel image.
2373 For example, to convert an RGB image into a greyscale image:
2375 $new = $img->convert(preset=>'grey'); # or gray
2377 or to convert a grayscale image to an RGB image:
2379 $new = $img->convert(preset=>'rgb');
2381 The presets aren't necessary simple constants in the code, some are
2382 generated based on the number of channels in the input image.
2384 If you want to perform some other colour transformation, you can use
2385 the 'matrix' parameter.
2387 For each output pixel the following matrix multiplication is done:
2389 channel[0] [ [ $c00, $c01, ... ] inchannel[0]
2390 [ ... ] = ... x [ ... ]
2391 channel[n-1] [ $cn0, ..., $cnn ] ] inchannel[max]
2394 So if you want to swap the red and green channels on a 3 channel image:
2396 $new = $img->convert(matrix=>[ [ 0, 1, 0 ],
2400 or to convert a 3 channel image to greyscale using equal weightings:
2402 $new = $img->convert(matrix=>[ [ 0.333, 0.333, 0.334 ] ])
2404 =head2 Color Mappings
2406 You can use the map method to map the values of each channel of an
2407 image independently using a list of lookup tables. It's important to
2408 realize that the modification is made inplace. The function simply
2409 returns the input image again or undef on failure.
2411 Each channel is mapped independently through a lookup table with 256
2412 entries. The elements in the table should not be less than 0 and not
2413 greater than 255. If they are out of the 0..255 range they are
2414 clamped to the range. If a table does not contain 256 entries it is
2417 Single channels can mapped by specifying their name and the mapping
2418 table. The channel names are C<red>, C<green>, C<blue>, C<alpha>.
2420 @map = map { int( $_/2 } 0..255;
2421 $img->map( red=>\@map );
2423 It is also possible to specify a single map that is applied to all
2424 channels, alpha channel included. For example this applies a gamma
2425 correction with a gamma of 1.4 to the input image.
2428 @map = map { int( 0.5 + 255*($_/255)**$gamma ) } 0..255;
2429 $img->map(all=> \@map);
2431 The C<all> map is used as a default channel, if no other map is
2432 specified for a channel then the C<all> map is used instead. If we
2433 had not wanted to apply gamma to the alpha channel we would have used:
2435 $img->map(all=> \@map, alpha=>[]);
2437 Since C<[]> contains fewer than 256 element the gamma channel is
2440 It is also possible to simply specify an array of maps that are
2441 applied to the images in the rgba order. For example to apply
2442 maps to the C<red> and C<blue> channels one would use:
2444 $img->map(maps=>[\@redmap, [], \@bluemap]);
2448 =head2 Transformations
2450 Another special image method is transform. It can be used to generate
2451 warps and rotations and such features. It can be given the operations
2452 in postfix notation or the module Affix::Infix2Postfix can be used.
2453 Look in the test case t/t55trans.t for an example.
2455 transform() needs expressions (or opcodes) that determine the source
2456 pixel for each target pixel. Source expressions are infix expressions
2457 using any of the +, -, *, / or ** binary operators, the - unary
2458 operator, ( and ) for grouping and the sin() and cos() functions. The
2459 target pixel is input as the variables x and y.
2461 You specify the x and y expressions as xexpr and yexpr respectively.
2462 You can also specify opcodes directly, but that's magic deep enough
2463 that you can look at the source code.
2465 You can still use the transform() function, but the transform2()
2466 function is just as fast and is more likely to be enhanced and
2469 Later versions of Imager also support a transform2() class method
2470 which allows you perform a more general set of operations, rather than
2471 just specifying a spatial transformation as with the transform()
2472 method, you can also perform colour transformations, image synthesis
2473 and image combinations.
2475 transform2() takes an reference to an options hash, and a list of
2476 images to operate one (this list may be empty):
2481 my $img = Imager::transform2(\%opts, @imgs)
2482 or die "transform2 failed: $Imager::ERRSTR";
2484 The options hash may define a transformation function, and optionally:
2490 width - the width of the image in pixels. If this isn't supplied the
2491 width of the first input image is used. If there are no input images
2496 height - the height of the image in pixels. If this isn't supplied
2497 the height of the first input image is used. If there are no input
2498 images an error occurs.
2502 constants - a reference to hash of constants to define for the
2503 expression engine. Some extra constants are defined by Imager
2507 The tranformation function is specified using either the expr or
2508 rpnexpr member of the options.
2512 =item Infix expressions
2514 You can supply infix expressions to transform 2 with the expr keyword.
2516 $opts{expr} = 'return getp1(w-x, h-y)'
2518 The 'expression' supplied follows this general grammar:
2520 ( identifier '=' expr ';' )* 'return' expr
2522 This allows you to simplify your expressions using variables.
2524 A more complex example might be:
2526 $opts{expr} = 'pix = getp1(x,y); return if(value(pix)>0.8,pix*0.8,pix)'
2528 Currently to use infix expressions you must have the Parse::RecDescent
2529 module installed (available from CPAN). There is also what might be a
2530 significant delay the first time you run the infix expression parser
2531 due to the compilation of the expression grammar.
2533 =item Postfix expressions
2535 You can supply postfix or reverse-polish notation expressions to
2536 transform2() through the rpnexpr keyword.
2538 The parser for rpnexpr emulates a stack machine, so operators will
2539 expect to see their parameters on top of the stack. A stack machine
2540 isn't actually used during the image transformation itself.
2542 You can store the value at the top of the stack in a variable called
2543 foo using !foo and retrieve that value again using @foo. The !foo
2544 notation will pop the value from the stack.
2546 An example equivalent to the infix expression above:
2548 $opts{rpnexpr} = 'x y getp1 !pix @pix value 0.8 gt @pix 0.8 * @pix ifp'
2552 transform2() has a fairly rich range of operators.
2556 =item +, *, -, /, %, **
2558 multiplication, addition, subtraction, division, remainder and
2559 exponentiation. Multiplication, addition and subtraction can be used
2560 on colour values too - though you need to be careful - adding 2 white
2561 values together and multiplying by 0.5 will give you grey, not white.
2563 Division by zero (or a small number) just results in a large number.
2564 Modulo zero (or a small number) results in zero.
2566 =item sin(N), cos(N), atan2(y,x)
2568 Some basic trig functions. They work in radians, so you can't just
2571 =item distance(x1, y1, x2, y2)
2573 Find the distance between two points. This is handy (along with
2574 atan2()) for producing circular effects.
2578 Find the square root. I haven't had much use for this since adding
2579 the distance() function.
2583 Find the absolute value.
2585 =item getp1(x,y), getp2(x,y), getp3(x, y)
2587 Get the pixel at position (x,y) from the first, second or third image
2588 respectively. I may add a getpn() function at some point, but this
2589 prevents static checking of the instructions against the number of
2590 images actually passed in.
2592 =item value(c), hue(c), sat(c), hsv(h,s,v)
2594 Separates a colour value into it's value (brightness), hue (colour)
2595 and saturation elements. Use hsv() to put them back together (after
2596 suitable manipulation).
2598 =item red(c), green(c), blue(c), rgb(r,g,b)
2600 Separates a colour value into it's red, green and blue colours. Use
2601 rgb(r,g,b) to put it back together.
2605 Convert a value to an integer. Uses a C int cast, so it may break on
2608 =item if(cond,ntrue,nfalse), if(cond,ctrue,cfalse)
2610 A simple (and inefficient) if function.
2612 =item <=,<,==,>=,>,!=
2614 Relational operators (typically used with if()). Since we're working
2615 with floating point values the equalities are 'near equalities' - an
2616 epsilon value is used.
2618 =item &&, ||, not(n)
2620 Basic logical operators.
2628 =item rpnexpr=>'x 25 % 15 * y 35 % 10 * getp1 !pat x y getp1 !pix @pix sat 0.7 gt @pat @pix ifp'
2630 tiles a smaller version of the input image over itself where the
2631 colour has a saturation over 0.7.
2633 =item rpnexpr=>'x 25 % 15 * y 35 % 10 * getp1 !pat y 360 / !rat x y getp1 1 @rat - pmult @pat @rat pmult padd'
2635 tiles the input image over itself so that at the top of the image the
2636 full-size image is at full strength and at the bottom the tiling is
2639 =item rpnexpr=>'x y getp1 !pix @pix value 0.96 gt @pix sat 0.1 lt and 128 128 255 rgb @pix ifp'
2641 replace pixels that are white or almost white with a palish blue
2643 =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'
2645 Tiles the input image overitself where the image isn't white or almost
2648 =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'
2652 =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'
2654 A spiral built on top of a colour wheel.
2658 For details on expression parsing see L<Imager::Expr>. For details on
2659 the virtual machine used to transform the images, see
2660 L<Imager::regmach.pod>.
2664 It is possible to add filters to the module without recompiling the
2665 module itself. This is done by using DSOs (Dynamic shared object)
2666 avaliable on most systems. This way you can maintain our own filters
2667 and not have to get me to add it, or worse patch every new version of
2668 the Module. Modules can be loaded AND UNLOADED at runtime. This
2669 means that you can have a server/daemon thingy that can do something
2672 load_plugin("dynfilt/dyntest.so") || die "unable to load plugin\n";
2673 %hsh=(a=>35,b=>200,type=>lin_stretch);
2675 unload_plugin("dynfilt/dyntest.so") || die "unable to load plugin\n";
2676 $img->write(type=>'pnm',file=>'testout/t60.jpg')
2677 || die "error in write()\n";
2679 Someone decides that the filter is not working as it should -
2680 dyntest.c modified and recompiled.
2682 load_plugin("dynfilt/dyntest.so") || die "unable to load plugin\n";
2685 An example plugin comes with the module - Please send feedback to
2686 addi@umich.edu if you test this.
2688 Note: This seems to test ok on the following systems:
2689 Linux, Solaris, HPUX, OpenBSD, FreeBSD, TRU64/OSF1, AIX.
2690 If you test this on other systems please let me know.
2694 box, arc, circle do not support antialiasing yet. arc, is only filled
2695 as of yet. Some routines do not return $self where they should. This
2696 affects code like this, C<$img-E<gt>box()-E<gt>arc()> where an object
2699 When saving Gif images the program does NOT try to shave of extra
2700 colors if it is possible. If you specify 128 colors and there are
2701 only 2 colors used - it will have a 128 colortable anyway.
2705 Arnar M. Hrafnkelsson, addi@umich.edu, and recently lots of assistance
2706 from Tony Cook. See the README for a complete list.
2710 perl(1), Imager::Color(3), Imager::Font, Affix::Infix2Postfix(3),
2711 Parse::RecDescent(3) http://www.eecs.umich.edu/~addi/perl/Imager/