4 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS %formats $DEBUG %filters %DSOs $ERRSTR $fontstate %OPCODES $I2P $FORMATGUESS);
82 i_writetiff_wiol_faxable
149 $VERSION = '0.39pre1';
150 @ISA = qw(Exporter DynaLoader);
151 bootstrap Imager $VERSION;
155 i_init_fonts(); # Initialize font engines
156 Imager::Font::__init();
157 for(i_list_formats()) { $formats{$_}++; }
159 if ($formats{'t1'}) {
163 if (!$formats{'t1'} and !$formats{'tt'}
164 && !$formats{'ft2'} && !$formats{'w32'}) {
165 $fontstate='no font support';
168 %OPCODES=(Add=>[0],Sub=>[1],Mult=>[2],Div=>[3],Parm=>[4],'sin'=>[5],'cos'=>[6],'x'=>[4,0],'y'=>[4,1]);
173 callseq => ['image','intensity'],
174 callsub => sub { my %hsh=@_; i_contrast($hsh{image},$hsh{intensity}); }
178 callseq => ['image', 'amount', 'subtype'],
179 defaults => { amount=>3,subtype=>0 },
180 callsub => sub { my %hsh=@_; i_noise($hsh{image},$hsh{amount},$hsh{subtype}); }
183 $filters{hardinvert} ={
184 callseq => ['image'],
186 callsub => sub { my %hsh=@_; i_hardinvert($hsh{image}); }
189 $filters{autolevels} ={
190 callseq => ['image','lsat','usat','skew'],
191 defaults => { lsat=>0.1,usat=>0.1,skew=>0.0 },
192 callsub => sub { my %hsh=@_; i_autolevels($hsh{image},$hsh{lsat},$hsh{usat},$hsh{skew}); }
195 $filters{turbnoise} ={
196 callseq => ['image'],
197 defaults => { xo=>0.0,yo=>0.0,scale=>10.0 },
198 callsub => sub { my %hsh=@_; i_turbnoise($hsh{image},$hsh{xo},$hsh{yo},$hsh{scale}); }
201 $filters{radnoise} ={
202 callseq => ['image'],
203 defaults => { xo=>100,yo=>100,ascale=>17.0,rscale=>0.02 },
204 callsub => sub { my %hsh=@_; i_radnoise($hsh{image},$hsh{xo},$hsh{yo},$hsh{rscale},$hsh{ascale}); }
208 callseq => ['image', 'coef'],
210 callsub => sub { my %hsh=@_; i_conv($hsh{image},$hsh{coef}); }
214 callseq => ['image', 'xo', 'yo', 'colors', 'dist'],
216 callsub => sub { my %hsh=@_; i_gradgen($hsh{image}, $hsh{xo}, $hsh{yo}, $hsh{colors}, $hsh{dist}); }
219 $filters{nearest_color} ={
220 callseq => ['image', 'xo', 'yo', 'colors', 'dist'],
222 callsub => sub { my %hsh=@_; i_nearest_color($hsh{image}, $hsh{xo}, $hsh{yo}, $hsh{colors}, $hsh{dist}); }
224 $filters{gaussian} = {
225 callseq => [ 'image', 'stddev' ],
227 callsub => sub { my %hsh = @_; i_gaussian($hsh{image}, $hsh{stddev}); },
230 $FORMATGUESS=\&def_guess_type;
238 # NOTE: this might be moved to an import override later on
242 # (look through @_ for special tags, process, and remove them);
244 # print Dumper($pack);
249 my %parms=(loglevel=>1,@_);
251 init_log($parms{'log'},$parms{'loglevel'});
254 # if ($parms{T1LIB_CONFIG}) { $ENV{T1LIB_CONFIG}=$parms{T1LIB_CONFIG}; }
255 # if ( $ENV{T1LIB_CONFIG} and ( $fontstate eq 'missing conf' )) {
263 print "shutdown code\n";
264 # for(keys %instances) { $instances{$_}->DESTROY(); }
265 malloc_state(); # how do decide if this should be used? -- store something from the import
266 print "Imager exiting\n";
270 # Load a filter plugin
275 my ($DSO_handle,$str)=DSO_open($filename);
276 if (!defined($DSO_handle)) { $Imager::ERRSTR="Couldn't load plugin '$filename'\n"; return undef; }
277 my %funcs=DSO_funclist($DSO_handle);
278 if ($DEBUG) { print "loading module $filename\n"; $i=0; for(keys %funcs) { printf(" %2d: %s\n",$i++,$_); } }
280 for(keys %funcs) { if ($filters{$_}) { $ERRSTR="filter '$_' already exists\n"; DSO_close($DSO_handle); return undef; } }
282 $DSOs{$filename}=[$DSO_handle,\%funcs];
285 my $evstr="\$filters{'".$_."'}={".$funcs{$_}.'};';
286 $DEBUG && print "eval string:\n",$evstr,"\n";
298 if (!$DSOs{$filename}) { $ERRSTR="plugin '$filename' not loaded."; return undef; }
299 my ($DSO_handle,$funcref)=@{$DSOs{$filename}};
300 for(keys %{$funcref}) {
302 $DEBUG && print "unloading: $_\n";
304 my $rc=DSO_close($DSO_handle);
305 if (!defined($rc)) { $ERRSTR="unable to unload plugin '$filename'."; return undef; }
309 # take the results of i_error() and make a message out of it
311 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, bits=>8, type=>'direct', @_);
422 if (defined($self->{IMG})) {
423 # let IIM_DESTROY destroy it, it's possible this image is
424 # referenced from a virtual image (like masked)
425 #i_img_destroy($self->{IMG});
429 if ($hsh{type} eq 'paletted' || $hsh{type} eq 'pseudo') {
430 $self->{IMG} = i_img_pal_new($hsh{xsize}, $hsh{ysize}, $hsh{channels},
431 $hsh{maxcolors} || 256);
433 elsif ($hsh{bits} == 16) {
434 $self->{IMG} = i_img_16_new($hsh{xsize}, $hsh{ysize}, $hsh{channels});
437 $self->{IMG}=Imager::ImgRaw::new($hsh{'xsize'}, $hsh{'ysize'},
442 # created a masked version of the current image
446 $self or return undef;
447 my %opts = (left => 0,
449 right => $self->getwidth,
450 bottom => $self->getheight,
452 my $mask = $opts{mask} ? $opts{mask}{IMG} : undef;
454 my $result = Imager->new;
455 $result->{IMG} = i_img_masked_new($self->{IMG}, $mask, $opts{left},
456 $opts{top}, $opts{right} - $opts{left},
457 $opts{bottom} - $opts{top});
458 # keep references to the mask and base images so they don't
460 $result->{DEPENDS} = [ $self->{IMG}, $mask ];
465 # convert an RGB image into a paletted image
469 if (@_ != 1 && !ref $_[0]) {
476 my $result = Imager->new;
477 $result->{IMG} = i_img_to_pal($self->{IMG}, $opts);
479 #print "Type ", i_img_type($result->{IMG}), "\n";
481 $result->{IMG} or undef $result;
486 # convert a paletted (or any image) to an 8-bit/channel RGB images
492 $result = Imager->new;
493 $result->{IMG} = i_img_to_rgb($self->{IMG})
502 my %opts = (colors=>[], @_);
504 @{$opts{colors}} or return undef;
506 $self->{IMG} and i_addcolors($self->{IMG}, @{$opts{colors}});
511 my %opts = (start=>0, colors=>[], @_);
512 @{$opts{colors}} or return undef;
514 $self->{IMG} and i_setcolors($self->{IMG}, $opts{start}, @{$opts{colors}});
520 if (!exists $opts{start} && !exists $opts{count}) {
523 $opts{count} = $self->colorcount;
525 elsif (!exists $opts{count}) {
528 elsif (!exists $opts{start}) {
533 return i_getcolors($self->{IMG}, $opts{start}, $opts{count});
537 i_colorcount($_[0]{IMG});
541 i_maxcolors($_[0]{IMG});
547 $opts{color} or return undef;
549 $self->{IMG} and i_findcolor($self->{IMG}, $opts{color});
554 $self->{IMG} and i_img_bits($self->{IMG});
560 return i_img_type($self->{IMG}) ? "paletted" : "direct";
566 $self->{IMG} and i_img_virtual($self->{IMG});
570 my ($self, %opts) = @_;
572 $self->{IMG} or return;
574 if (defined $opts{name}) {
578 while (defined($found = i_tags_find($self->{IMG}, $opts{name}, $start))) {
579 push @result, (i_tags_get($self->{IMG}, $found))[1];
582 return wantarray ? @result : $result[0];
584 elsif (defined $opts{code}) {
588 while (defined($found = i_tags_findn($self->{IMG}, $opts{code}, $start))) {
589 push @result, (i_tags_get($self->{IMG}, $found))[1];
596 return map { [ i_tags_get($self->{IMG}, $_) ] } 0.. i_tags_count($self->{IMG})-1;
599 return i_tags_count($self->{IMG});
608 return -1 unless $self->{IMG};
610 if (defined $opts{value}) {
611 if ($opts{value} =~ /^\d+$/) {
613 return i_tags_addn($self->{IMG}, $opts{name}, 0, $opts{value});
616 return i_tags_add($self->{IMG}, $opts{name}, 0, $opts{value}, 0);
619 elsif (defined $opts{data}) {
620 # force addition as a string
621 return i_tags_add($self->{IMG}, $opts{name}, 0, $opts{data}, 0);
624 $self->{ERRSTR} = "No value supplied";
628 elsif ($opts{code}) {
629 if (defined $opts{value}) {
630 if ($opts{value} =~ /^\d+$/) {
632 return i_tags_addn($self->{IMG}, $opts{code}, 0, $opts{value});
635 return i_tags_add($self->{IMG}, $opts{code}, 0, $opts{value}, 0);
638 elsif (defined $opts{data}) {
639 # force addition as a string
640 return i_tags_add($self->{IMG}, $opts{code}, 0, $opts{data}, 0);
643 $self->{ERRSTR} = "No value supplied";
656 return 0 unless $self->{IMG};
658 if (defined $opts{index}) {
659 return i_tags_delete($self->{IMG}, $opts{index});
661 elsif (defined $opts{name}) {
662 return i_tags_delbyname($self->{IMG}, $opts{name});
664 elsif (defined $opts{code}) {
665 return i_tags_delbycode($self->{IMG}, $opts{code});
668 $self->{ERRSTR} = "Need to supply index, name, or code parameter";
673 # Read an image from file
680 if (defined($self->{IMG})) {
681 # let IIM_DESTROY do the destruction, since the image may be
682 # referenced from elsewhere
683 #i_img_destroy($self->{IMG});
687 if (!$input{fd} and !$input{file} and !$input{data}) {
688 $self->{ERRSTR}='no file, fd or data parameter'; return undef;
691 $fh = new IO::File($input{file},"r");
693 $self->{ERRSTR}='Could not open file'; return undef;
702 # FIXME: Find the format here if not specified
703 # yes the code isn't here yet - next week maybe?
704 # Next week? Are you high or something? That comment
705 # has been there for half a year dude.
708 if (!$input{type} and $input{file}) {
709 $input{type}=$FORMATGUESS->($input{file});
711 if (!$formats{$input{type}}) {
712 $self->{ERRSTR}='format not supported'; return undef;
715 my %iolready=(jpeg=>1, png=>1, tiff=>1, pnm=>1, raw=>1);
717 if ($iolready{$input{type}}) {
719 $IO = io_new_fd($fd); # sort of simple for now eh?
721 if ( $input{type} eq 'jpeg' ) {
722 ($self->{IMG},$self->{IPTCRAW})=i_readjpeg_wiol( $IO );
723 if ( !defined($self->{IMG}) ) {
724 $self->{ERRSTR}='unable to read jpeg image'; return undef;
726 $self->{DEBUG} && print "loading a jpeg file\n";
730 if ( $input{type} eq 'tiff' ) {
731 $self->{IMG}=i_readtiff_wiol( $IO, -1 ); # Fixme, check if that length parameter is ever needed
732 if ( !defined($self->{IMG}) ) {
733 $self->{ERRSTR}='unable to read tiff image'; return undef;
735 $self->{DEBUG} && print "loading a tiff file\n";
739 if ( $input{type} eq 'pnm' ) {
740 $self->{IMG}=i_readpnm_wiol( $IO, -1 ); # Fixme, check if that length parameter is ever needed
741 if ( !defined($self->{IMG}) ) {
742 $self->{ERRSTR}='unable to read pnm image: '._error_as_msg(); return undef;
744 $self->{DEBUG} && print "loading a pnm file\n";
748 if ( $input{type} eq 'png' ) {
749 $self->{IMG}=i_readpng_wiol( $IO, -1 ); # Fixme, check if that length parameter is ever needed
750 if ( !defined($self->{IMG}) ) {
751 $self->{ERRSTR}='unable to read png image';
754 $self->{DEBUG} && print "loading a png file\n";
757 if ( $input{type} eq 'raw' ) {
758 my %params=(datachannels=>3,storechannels=>3,interleave=>1,%input);
760 if ( !($params{xsize} && $params{ysize}) ) {
761 $self->{ERRSTR}='missing xsize or ysize parameter for raw';
765 $self->{IMG} = i_readraw_wiol( $IO,
768 $params{datachannels},
769 $params{storechannels},
770 $params{interleave});
771 if ( !defined($self->{IMG}) ) {
772 $self->{ERRSTR}='unable to read raw image';
775 $self->{DEBUG} && print "loading a raw file\n";
780 # Old code for reference while changing the new stuff
783 if (!$input{type} and $input{file}) {
784 $input{type}=$FORMATGUESS->($input{file});
788 $self->{ERRSTR}='type parameter missing and not possible to guess from extension'; return undef;
791 if (!$formats{$input{type}}) {
792 $self->{ERRSTR}='format not supported';
797 $fh = new IO::File($input{file},"r");
799 $self->{ERRSTR}='Could not open file';
810 if ( $input{type} eq 'gif' ) {
812 if ($input{colors} && !ref($input{colors})) {
813 # must be a reference to a scalar that accepts the colour map
814 $self->{ERRSTR} = "option 'colors' must be a scalar reference";
817 if (exists $input{data}) {
818 if ($input{colors}) {
819 ($self->{IMG}, $colors) = i_readgif_scalar($input{data});
821 $self->{IMG}=i_readgif_scalar($input{data});
824 if ($input{colors}) {
825 ($self->{IMG}, $colors) = i_readgif( $fd );
827 $self->{IMG} = i_readgif( $fd )
831 # we may or may not change i_readgif to return blessed objects...
832 ${ $input{colors} } = [ map { NC(@$_) } @$colors ];
834 if ( !defined($self->{IMG}) ) {
835 $self->{ERRSTR}= 'reading GIF:'._error_as_msg();
838 $self->{DEBUG} && print "loading a gif file\n";
841 if ( $input{type} eq 'jpeg' ) {
842 if ( !i_writejpeg_wiol($self->{IMG}, $IO, $input{jpegquality})) {
843 $self->{ERRSTR}='unable to write jpeg image';
846 $self->{DEBUG} && print "writing a jpeg file\n";
854 # Write an image to file
858 my %input=(jpegquality=>75, gifquant=>'mc', lmdither=>6.0, lmfixed=>[],
860 my ($fh, $rc, $fd, $IO);
862 my %iolready=( tiff=>1, raw=>1, png=>1, pnm=>1 ); # this will be SO MUCH BETTER once they are all in there
864 unless ($self->{IMG}) { $self->{ERRSTR}='empty input image'; return undef; }
866 if (!$input{file} and !$input{'fd'} and !$input{'data'}) { $self->{ERRSTR}='file/fd/data parameter missing'; return undef; }
867 if (!$input{type} and $input{file}) { $input{type}=$FORMATGUESS->($input{file}); }
868 if (!$input{type}) { $self->{ERRSTR}='type parameter missing and not possible to guess from extension'; return undef; }
870 if (!$formats{$input{type}}) { $self->{ERRSTR}='format not supported'; return undef; }
872 if (exists $input{'fd'}) {
874 } elsif (exists $input{'data'}) {
875 $IO = Imager::io_new_bufchain();
877 $fh = new IO::File($input{file},"w+");
878 if (!defined $fh) { $self->{ERRSTR}='Could not open file'; return undef; }
883 if ($iolready{$input{type}}) {
885 $IO = io_new_fd($fd);
888 if ($input{type} eq 'tiff') {
889 if (defined $input{class} && $input{class} eq 'fax') {
890 if (!i_writetiff_wiol_faxable($self->{IMG}, $IO, $input{fax_fine})) {
891 $self->{ERRSTR}='Could not write to buffer';
895 if (!i_writetiff_wiol($self->{IMG}, $IO)) {
896 $self->{ERRSTR}='Could not write to buffer';
900 } elsif ( $input{type} eq 'pnm' ) {
901 if ( ! i_writeppm_wiol($self->{IMG},$IO) ) {
902 $self->{ERRSTR}='unable to write pnm image';
905 $self->{DEBUG} && print "writing a pnm file\n";
906 } elsif ( $input{type} eq 'raw' ) {
907 if ( !i_writeraw_wiol($self->{IMG},$IO) ) {
908 $self->{ERRSTR}='unable to write raw image';
911 $self->{DEBUG} && print "writing a raw file\n";
912 } elsif ( $input{type} eq 'png' ) {
913 if ( !i_writepng_wiol($self->{IMG}, $IO) ) {
914 $self->{ERRSTR}='unable to write png image';
917 $self->{DEBUG} && print "writing a png file\n";
920 if (exists $input{'data'}) {
921 my $data = io_slurp($IO);
923 $self->{ERRSTR}='Could not slurp from buffer';
926 ${$input{data}} = $data;
931 if ( $input{type} eq 'gif' ) {
932 if (not $input{gifplanes}) {
934 my $count=i_count_colors($self->{IMG}, 256);
935 $gp=8 if $count == -1;
936 $gp=1 if not $gp and $count <= 2;
937 $gp=2 if not $gp and $count <= 4;
938 $gp=3 if not $gp and $count <= 8;
939 $gp=4 if not $gp and $count <= 16;
940 $gp=5 if not $gp and $count <= 32;
941 $gp=6 if not $gp and $count <= 64;
942 $gp=7 if not $gp and $count <= 128;
943 $input{gifplanes} = $gp || 8;
946 if ($input{gifplanes}>8) {
949 if ($input{gifquant} eq 'gen' || $input{callback}) {
952 if ($input{gifquant} eq 'lm') {
954 $input{make_colors} = 'addi';
955 $input{translate} = 'perturb';
956 $input{perturb} = $input{lmdither};
957 } elsif ($input{gifquant} eq 'gen') {
958 # just pass options through
960 $input{make_colors} = 'webmap'; # ignored
961 $input{translate} = 'giflib';
964 if ($input{callback}) {
965 defined $input{maxbuffer} or $input{maxbuffer} = -1;
966 $rc = i_writegif_callback($input{callback}, $input{maxbuffer},
967 \%input, $self->{IMG});
969 $rc = i_writegif_gen($fd, \%input, $self->{IMG});
972 } elsif ($input{gifquant} eq 'lm') {
973 $rc=i_writegif($self->{IMG},$fd,$input{gifplanes},$input{lmdither},$input{lmfixed});
975 $rc=i_writegifmc($self->{IMG},$fd,$input{gifplanes});
977 if ( !defined($rc) ) {
978 $self->{ERRSTR} = "Writing GIF file: "._error_as_msg(); return undef;
980 $self->{DEBUG} && print "writing a gif file\n";
988 my ($class, $opts, @images) = @_;
990 if ($opts->{type} eq 'gif') {
991 my $gif_delays = $opts->{gif_delays};
992 local $opts->{gif_delays} = $gif_delays;
993 unless (ref $opts->{gif_delays}) {
994 # assume the caller wants the same delay for each frame
995 $opts->{gif_delays} = [ ($gif_delays) x @images ];
997 # translate to ImgRaw
998 if (grep !UNIVERSAL::isa($_, 'Imager') || !$_->{IMG}, @images) {
999 $ERRSTR = "Usage: Imager->write_multi({ options }, @images)";
1002 my @work = map $_->{IMG}, @images;
1003 if ($opts->{callback}) {
1004 # Note: you may need to fix giflib for this one to work
1005 my $maxbuffer = $opts->{maxbuffer};
1006 defined $maxbuffer or $maxbuffer = -1; # max by default
1007 return i_writegif_callback($opts->{callback}, $maxbuffer,
1011 return i_writegif_gen($opts->{fd}, $opts, @work);
1014 my $fh = IO::File->new($opts->{file}, "w+");
1016 $ERRSTR = "Error creating $opts->{file}: $!";
1020 return i_writegif_gen(fileno($fh), $opts, @work);
1024 $ERRSTR = "Sorry, write_multi doesn't support $opts->{type} yet";
1029 # read multiple images from a file
1031 my ($class, %opts) = @_;
1033 if ($opts{file} && !exists $opts{type}) {
1035 my $type = $FORMATGUESS->($opts{file});
1036 $opts{type} = $type;
1038 unless ($opts{type}) {
1039 $ERRSTR = "No type parameter supplied and it couldn't be guessed";
1045 $file = IO::File->new($opts{file}, "r");
1047 $ERRSTR = "Could not open file $opts{file}: $!";
1051 $fd = fileno($file);
1054 $fd = fileno($opts{fh});
1056 $ERRSTR = "File handle specified with fh option not open";
1063 elsif ($opts{callback} || $opts{data}) {
1067 $ERRSTR = "You need to specify one of file, fd, fh, callback or data";
1071 if ($opts{type} eq 'gif') {
1074 @imgs = i_readgif_multi($fd);
1077 if (Imager::i_giflib_version() < 4.0) {
1078 $ERRSTR = "giflib3.x does not support callbacks";
1081 if ($opts{callback}) {
1082 @imgs = i_readgif_multi_callback($opts{callback})
1085 @imgs = i_readgif_multi_scalar($opts{data});
1090 bless { IMG=>$_, DEBUG=>$DEBUG, ERRSTR=>undef }, 'Imager'
1094 $ERRSTR = _error_as_msg();
1099 $ERRSTR = "Cannot read multiple images from $opts{type} files";
1103 # Destroy an Imager object
1107 # delete $instances{$self};
1108 if (defined($self->{IMG})) {
1109 # the following is now handled by the XS DESTROY method for
1110 # Imager::ImgRaw object
1111 # Re-enabling this will break virtual images
1112 # tested for in t/t020masked.t
1113 # i_img_destroy($self->{IMG});
1114 undef($self->{IMG});
1116 # print "Destroy Called on an empty image!\n"; # why did I put this here??
1120 # Perform an inplace filter of an image
1121 # that is the image will be overwritten with the data
1127 unless ($self->{IMG}) { $self->{ERRSTR}='empty input image'; return undef; }
1129 if (!$input{type}) { $self->{ERRSTR}='type parameter missing'; return undef; }
1131 if ( (grep { $_ eq $input{type} } keys %filters) != 1) {
1132 $self->{ERRSTR}='type parameter not matching any filter'; return undef;
1135 if (defined($filters{$input{type}}{defaults})) {
1136 %hsh=('image',$self->{IMG},%{$filters{$input{type}}{defaults}},%input);
1138 %hsh=('image',$self->{IMG},%input);
1141 my @cs=@{$filters{$input{type}}{callseq}};
1144 if (!defined($hsh{$_})) {
1145 $self->{ERRSTR}="missing parameter '$_' for filter ".$input{type}; return undef;
1149 &{$filters{$input{type}}{callsub}}(%hsh);
1153 $self->{DEBUG} && print "callseq is: @cs\n";
1154 $self->{DEBUG} && print "matching callseq is: @b\n";
1159 # Scale an image to requested size and return the scaled version
1163 my %opts=(scalefactor=>0.5,type=>'max',qtype=>'normal',@_);
1164 my $img = Imager->new();
1165 my $tmp = Imager->new();
1167 unless ($self->{IMG}) { $self->{ERRSTR}='empty input image'; return undef; }
1169 if ($opts{xpixels} and $opts{ypixels} and $opts{type}) {
1170 my ($xpix,$ypix)=( $opts{xpixels}/$self->getwidth() , $opts{ypixels}/$self->getheight() );
1171 if ($opts{type} eq 'min') { $opts{scalefactor}=min($xpix,$ypix); }
1172 if ($opts{type} eq 'max') { $opts{scalefactor}=max($xpix,$ypix); }
1173 } elsif ($opts{xpixels}) { $opts{scalefactor}=$opts{xpixels}/$self->getwidth(); }
1174 elsif ($opts{ypixels}) { $opts{scalefactor}=$opts{ypixels}/$self->getheight(); }
1176 if ($opts{qtype} eq 'normal') {
1177 $tmp->{IMG}=i_scaleaxis($self->{IMG},$opts{scalefactor},0);
1178 if ( !defined($tmp->{IMG}) ) { $self->{ERRSTR}='unable to scale image'; return undef; }
1179 $img->{IMG}=i_scaleaxis($tmp->{IMG},$opts{scalefactor},1);
1180 if ( !defined($img->{IMG}) ) { $self->{ERRSTR}='unable to scale image'; return undef; }
1183 if ($opts{'qtype'} eq 'preview') {
1184 $img->{IMG}=i_scale_nn($self->{IMG},$opts{'scalefactor'},$opts{'scalefactor'});
1185 if ( !defined($img->{IMG}) ) { $self->{ERRSTR}='unable to scale image'; return undef; }
1188 $self->{ERRSTR}='scale: invalid value for qtype'; return undef;
1191 # Scales only along the X axis
1195 my %opts=(scalefactor=>0.5,@_);
1197 unless ($self->{IMG}) { $self->{ERRSTR}='empty input image'; return undef; }
1199 my $img = Imager->new();
1201 if ($opts{pixels}) { $opts{scalefactor}=$opts{pixels}/$self->getwidth(); }
1203 unless ($self->{IMG}) { $self->{ERRSTR}='empty input image'; return undef; }
1204 $img->{IMG}=i_scaleaxis($self->{IMG},$opts{scalefactor},0);
1206 if ( !defined($img->{IMG}) ) { $self->{ERRSTR}='unable to scale image'; return undef; }
1210 # Scales only along the Y axis
1214 my %opts=(scalefactor=>0.5,@_);
1216 unless ($self->{IMG}) { $self->{ERRSTR}='empty input image'; return undef; }
1218 my $img = Imager->new();
1220 if ($opts{pixels}) { $opts{scalefactor}=$opts{pixels}/$self->getheight(); }
1222 unless ($self->{IMG}) { $self->{ERRSTR}='empty input image'; return undef; }
1223 $img->{IMG}=i_scaleaxis($self->{IMG},$opts{scalefactor},1);
1225 if ( !defined($img->{IMG}) ) { $self->{ERRSTR}='unable to scale image'; return undef; }
1230 # Transform returns a spatial transformation of the input image
1231 # this moves pixels to a new location in the returned image.
1232 # NOTE - should make a utility function to check transforms for
1237 unless ($self->{IMG}) { $self->{ERRSTR}='empty input image'; return undef; }
1239 my (@op,@ropx,@ropy,$iop,$or,@parm,$expr,@xt,@yt,@pt,$numre);
1241 # print Dumper(\%opts);
1244 if ( $opts{'xexpr'} and $opts{'yexpr'} ) {
1246 eval ("use Affix::Infix2Postfix;");
1249 $self->{ERRSTR}='transform: expr given and Affix::Infix2Postfix is not avaliable.';
1252 $I2P=Affix::Infix2Postfix->new('ops'=>[{op=>'+',trans=>'Add'},
1253 {op=>'-',trans=>'Sub'},
1254 {op=>'*',trans=>'Mult'},
1255 {op=>'/',trans=>'Div'},
1256 {op=>'-',type=>'unary',trans=>'u-'},
1258 {op=>'func',type=>'unary'}],
1259 'grouping'=>[qw( \( \) )],
1260 'func'=>[qw( sin cos )],
1265 @xt=$I2P->translate($opts{'xexpr'});
1266 @yt=$I2P->translate($opts{'yexpr'});
1268 $numre=$I2P->{'numre'};
1271 for(@xt) { if (/$numre/) { push(@pt,$_); push(@{$opts{'xopcodes'}},'Parm',$#pt); } else { push(@{$opts{'xopcodes'}},$_); } }
1272 for(@yt) { if (/$numre/) { push(@pt,$_); push(@{$opts{'yopcodes'}},'Parm',$#pt); } else { push(@{$opts{'yopcodes'}},$_); } }
1273 @{$opts{'parm'}}=@pt;
1276 # print Dumper(\%opts);
1278 if ( !exists $opts{'xopcodes'} or @{$opts{'xopcodes'}}==0) {
1279 $self->{ERRSTR}='transform: no xopcodes given.';
1283 @op=@{$opts{'xopcodes'}};
1285 if (!defined ($OPCODES{$iop}) and ($iop !~ /^\d+$/) ) {
1286 $self->{ERRSTR}="transform: illegal opcode '$_'.";
1289 push(@ropx,(exists $OPCODES{$iop}) ? @{$OPCODES{$iop}} : $iop );
1295 if ( !exists $opts{'yopcodes'} or @{$opts{'yopcodes'}}==0) {
1296 $self->{ERRSTR}='transform: no yopcodes given.';
1300 @op=@{$opts{'yopcodes'}};
1302 if (!defined ($OPCODES{$iop}) and ($iop !~ /^\d+$/) ) {
1303 $self->{ERRSTR}="transform: illegal opcode '$_'.";
1306 push(@ropy,(exists $OPCODES{$iop}) ? @{$OPCODES{$iop}} : $iop );
1311 if ( !exists $opts{'parm'}) {
1312 $self->{ERRSTR}='transform: no parameter arg given.';
1316 # print Dumper(\@ropx);
1317 # print Dumper(\@ropy);
1318 # print Dumper(\@ropy);
1320 my $img = Imager->new();
1321 $img->{IMG}=i_transform($self->{IMG},\@ropx,\@ropy,$opts{'parm'});
1322 if ( !defined($img->{IMG}) ) { $self->{ERRSTR}='transform: failed'; return undef; }
1330 my ($opts, @imgs) = @_;
1333 # this is fairly big, delay loading it
1334 eval "use Imager::Expr";
1339 $opts->{variables} = [ qw(x y) ];
1340 my ($width, $height) = @{$opts}{qw(width height)};
1342 $width ||= $imgs[0]->getwidth();
1343 $height ||= $imgs[0]->getheight();
1345 for my $img (@imgs) {
1346 $opts->{constants}{"w$img_num"} = $img->getwidth();
1347 $opts->{constants}{"h$img_num"} = $img->getheight();
1348 $opts->{constants}{"cx$img_num"} = $img->getwidth()/2;
1349 $opts->{constants}{"cy$img_num"} = $img->getheight()/2;
1354 $opts->{constants}{w} = $width;
1355 $opts->{constants}{cx} = $width/2;
1358 $Imager::ERRSTR = "No width supplied";
1362 $opts->{constants}{h} = $height;
1363 $opts->{constants}{cy} = $height/2;
1366 $Imager::ERRSTR = "No height supplied";
1369 my $code = Imager::Expr->new($opts);
1371 $Imager::ERRSTR = Imager::Expr::error();
1375 my $img = Imager->new();
1376 $img->{IMG} = i_transform2($opts->{width}, $opts->{height}, $code->code(),
1377 $code->nregs(), $code->cregs(),
1378 [ map { $_->{IMG} } @imgs ]);
1379 if (!defined $img->{IMG}) {
1380 $Imager::ERRSTR = "transform2 failed";
1390 my %opts=(tx=>0,ty=>0,@_);
1392 unless ($self->{IMG}) { $self->{ERRSTR}='empty input image'; return undef; }
1393 unless ($opts{src} && $opts{src}->{IMG}) { $self->{ERRSTR}='empty input image for source'; return undef; }
1395 unless (i_rubthru($self->{IMG}, $opts{src}->{IMG}, $opts{tx},$opts{ty})) {
1396 $self->{ERRSTR} = $self->_error_as_msg();
1406 my %xlate = (h=>0, v=>1, hv=>2, vh=>2);
1408 return () unless defined $opts{'dir'} and defined $xlate{$opts{'dir'}};
1409 $dir = $xlate{$opts{'dir'}};
1410 return $self if i_flipxy($self->{IMG}, $dir);
1417 if (defined $opts{right}) {
1418 my $degrees = $opts{right};
1420 $degrees += 360 * int(((-$degrees)+360)/360);
1422 $degrees = $degrees % 360;
1423 if ($degrees == 0) {
1424 return $self->copy();
1426 elsif ($degrees == 90 || $degrees == 180 || $degrees == 270) {
1427 my $result = Imager->new();
1428 if ($result->{IMG} = i_rotate90($self->{IMG}, $degrees)) {
1432 $self->{ERRSTR} = $self->_error_as_msg();
1437 $self->{ERRSTR} = "Parameter 'right' must be a multiple of 90 degrees";
1441 elsif (defined $opts{radians} || defined $opts{degrees}) {
1442 my $amount = $opts{radians} || $opts{degrees} * 3.1415926535 / 180;
1444 my $result = Imager->new;
1445 if ($result->{IMG} = i_rotate_exact($self->{IMG}, $amount)) {
1449 $self->{ERRSTR} = $self->_error_as_msg();
1454 $self->{ERRSTR} = "Only the 'right' parameter is available";
1459 sub matrix_transform {
1463 if ($opts{matrix}) {
1464 my $xsize = $opts{xsize} || $self->getwidth;
1465 my $ysize = $opts{ysize} || $self->getheight;
1467 my $result = Imager->new;
1468 $result->{IMG} = i_matrix_transform($self->{IMG}, $xsize, $ysize,
1475 $self->{ERRSTR} = "matrix parameter required";
1481 *yatf = \&matrix_transform;
1483 # These two are supported for legacy code only
1486 return Imager::Color->new(@_);
1490 return Imager::Color::set(@_);
1493 # Draws a box between the specified corner points.
1496 unless ($self->{IMG}) { $self->{ERRSTR}='empty input image'; return undef; }
1497 my $dflcl=i_color_new(255,255,255,255);
1498 my %opts=(color=>$dflcl,xmin=>0,ymin=>0,xmax=>$self->getwidth()-1,ymax=>$self->getheight()-1,@_);
1500 if (exists $opts{'box'}) {
1501 $opts{'xmin'} = min($opts{'box'}->[0],$opts{'box'}->[2]);
1502 $opts{'xmax'} = max($opts{'box'}->[0],$opts{'box'}->[2]);
1503 $opts{'ymin'} = min($opts{'box'}->[1],$opts{'box'}->[3]);
1504 $opts{'ymax'} = max($opts{'box'}->[1],$opts{'box'}->[3]);
1507 if ($opts{filled}) { i_box_filled($self->{IMG},$opts{xmin},$opts{ymin},$opts{xmax},$opts{ymax},$opts{color}); }
1508 else { i_box($self->{IMG},$opts{xmin},$opts{ymin},$opts{xmax},$opts{ymax},$opts{color}); }
1512 # Draws an arc - this routine SUCKS and is buggy - it sometimes doesn't work when the arc is a convex polygon
1516 unless ($self->{IMG}) { $self->{ERRSTR}='empty input image'; return undef; }
1517 my $dflcl=i_color_new(255,255,255,255);
1518 my %opts=(color=>$dflcl,
1519 'r'=>min($self->getwidth(),$self->getheight())/3,
1520 'x'=>$self->getwidth()/2,
1521 'y'=>$self->getheight()/2,
1522 'd1'=>0, 'd2'=>361, @_);
1523 i_arc($self->{IMG},$opts{'x'},$opts{'y'},$opts{'r'},$opts{'d1'},$opts{'d2'},$opts{'color'});
1527 # Draws a line from one point to (but not including) the destination point
1531 my $dflcl=i_color_new(0,0,0,0);
1532 my %opts=(color=>$dflcl,@_);
1533 unless ($self->{IMG}) { $self->{ERRSTR}='empty input image'; return undef; }
1535 unless (exists $opts{x1} and exists $opts{y1}) { $self->{ERRSTR}='missing begining coord'; return undef; }
1536 unless (exists $opts{x2} and exists $opts{y2}) { $self->{ERRSTR}='missing ending coord'; return undef; }
1538 if ($opts{antialias}) {
1539 i_line_aa($self->{IMG},$opts{x1}, $opts{y1}, $opts{x2}, $opts{y2}, $opts{color});
1541 i_draw($self->{IMG},$opts{x1}, $opts{y1}, $opts{x2}, $opts{y2}, $opts{color});
1546 # Draws a line between an ordered set of points - It more or less just transforms this
1547 # into a list of lines.
1551 my ($pt,$ls,@points);
1552 my $dflcl=i_color_new(0,0,0,0);
1553 my %opts=(color=>$dflcl,@_);
1555 unless ($self->{IMG}) { $self->{ERRSTR}='empty input image'; return undef; }
1557 if (exists($opts{points})) { @points=@{$opts{points}}; }
1558 if (!exists($opts{points}) and exists($opts{'x'}) and exists($opts{'y'}) ) {
1559 @points=map { [ $opts{'x'}->[$_],$opts{'y'}->[$_] ] } (0..(scalar @{$opts{'x'}}-1));
1562 # print Dumper(\@points);
1564 if ($opts{antialias}) {
1566 if (defined($ls)) { i_line_aa($self->{IMG},$ls->[0],$ls->[1],$pt->[0],$pt->[1],$opts{color}); }
1571 if (defined($ls)) { i_draw($self->{IMG},$ls->[0],$ls->[1],$pt->[0],$pt->[1],$opts{color}); }
1578 # this the multipoint bezier curve
1579 # this is here more for testing that actual usage since
1580 # this is not a good algorithm. Usually the curve would be
1581 # broken into smaller segments and each done individually.
1585 my ($pt,$ls,@points);
1586 my $dflcl=i_color_new(0,0,0,0);
1587 my %opts=(color=>$dflcl,@_);
1589 unless ($self->{IMG}) { $self->{ERRSTR}='empty input image'; return undef; }
1591 if (exists $opts{points}) {
1592 $opts{'x'}=map { $_->[0]; } @{$opts{'points'}};
1593 $opts{'y'}=map { $_->[1]; } @{$opts{'points'}};
1596 unless ( @{$opts{'x'}} and @{$opts{'x'}} == @{$opts{'y'}} ) {
1597 $self->{ERRSTR}='Missing or invalid points.';
1601 i_bezier_multi($self->{IMG},$opts{'x'},$opts{'y'},$opts{'color'});
1605 # make an identity matrix of the given size
1609 my $matrix = [ map { [ (0) x $size ] } 1..$size ];
1610 for my $c (0 .. ($size-1)) {
1611 $matrix->[$c][$c] = 1;
1616 # general function to convert an image
1618 my ($self, %opts) = @_;
1621 # the user can either specify a matrix or preset
1622 # the matrix overrides the preset
1623 if (!exists($opts{matrix})) {
1624 unless (exists($opts{preset})) {
1625 $self->{ERRSTR} = "convert() needs a matrix or preset";
1629 if ($opts{preset} eq 'gray' || $opts{preset} eq 'grey') {
1630 # convert to greyscale, keeping the alpha channel if any
1631 if ($self->getchannels == 3) {
1632 $matrix = [ [ 0.222, 0.707, 0.071 ] ];
1634 elsif ($self->getchannels == 4) {
1635 # preserve the alpha channel
1636 $matrix = [ [ 0.222, 0.707, 0.071, 0 ],
1641 $matrix = _identity($self->getchannels);
1644 elsif ($opts{preset} eq 'noalpha') {
1645 # strip the alpha channel
1646 if ($self->getchannels == 2 or $self->getchannels == 4) {
1647 $matrix = _identity($self->getchannels);
1648 pop(@$matrix); # lose the alpha entry
1651 $matrix = _identity($self->getchannels);
1654 elsif ($opts{preset} eq 'red' || $opts{preset} eq 'channel0') {
1656 $matrix = [ [ 1 ] ];
1658 elsif ($opts{preset} eq 'green' || $opts{preset} eq 'channel1') {
1659 $matrix = [ [ 0, 1 ] ];
1661 elsif ($opts{preset} eq 'blue' || $opts{preset} eq 'channel2') {
1662 $matrix = [ [ 0, 0, 1 ] ];
1664 elsif ($opts{preset} eq 'alpha') {
1665 if ($self->getchannels == 2 or $self->getchannels == 4) {
1666 $matrix = [ [ (0) x ($self->getchannels-1), 1 ] ];
1669 # the alpha is just 1 <shrug>
1670 $matrix = [ [ (0) x $self->getchannels, 1 ] ];
1673 elsif ($opts{preset} eq 'rgb') {
1674 if ($self->getchannels == 1) {
1675 $matrix = [ [ 1 ], [ 1 ], [ 1 ] ];
1677 elsif ($self->getchannels == 2) {
1678 # preserve the alpha channel
1679 $matrix = [ [ 1, 0 ], [ 1, 0 ], [ 1, 0 ], [ 0, 1 ] ];
1682 $matrix = _identity($self->getchannels);
1685 elsif ($opts{preset} eq 'addalpha') {
1686 if ($self->getchannels == 1) {
1687 $matrix = _identity(2);
1689 elsif ($self->getchannels == 3) {
1690 $matrix = _identity(4);
1693 $matrix = _identity($self->getchannels);
1697 $self->{ERRSTR} = "Unknown convert preset $opts{preset}";
1703 $matrix = $opts{matrix};
1706 my $new = Imager->new();
1707 $new->{IMG} = i_img_new();
1708 unless (i_convert($new->{IMG}, $self->{IMG}, $matrix)) {
1709 # most likely a bad matrix
1710 $self->{ERRSTR} = _error_as_msg();
1717 # general function to map an image through lookup tables
1720 my ($self, %opts) = @_;
1721 my @chlist = qw( red green blue alpha );
1723 if (!exists($opts{'maps'})) {
1724 # make maps from channel maps
1726 for $chnum (0..$#chlist) {
1727 if (exists $opts{$chlist[$chnum]}) {
1728 $opts{'maps'}[$chnum] = $opts{$chlist[$chnum]};
1729 } elsif (exists $opts{'all'}) {
1730 $opts{'maps'}[$chnum] = $opts{'all'};
1734 if ($opts{'maps'} and $self->{IMG}) {
1735 i_map($self->{IMG}, $opts{'maps'} );
1740 # destructive border - image is shrunk by one pixel all around
1743 my ($self,%opts)=@_;
1744 my($tx,$ty)=($self->getwidth()-1,$self->getheight()-1);
1745 $self->polyline('x'=>[0,$tx,$tx,0,0],'y'=>[0,0,$ty,$ty,0],%opts);
1749 # Get the width of an image
1753 if (!defined($self->{IMG})) { $self->{ERRSTR} = 'image is empty'; return undef; }
1754 return (i_img_info($self->{IMG}))[0];
1757 # Get the height of an image
1761 if (!defined($self->{IMG})) { $self->{ERRSTR} = 'image is empty'; return undef; }
1762 return (i_img_info($self->{IMG}))[1];
1765 # Get number of channels in an image
1769 if (!defined($self->{IMG})) { $self->{ERRSTR} = 'image is empty'; return undef; }
1770 return i_img_getchannels($self->{IMG});
1777 if (!defined($self->{IMG})) { $self->{ERRSTR} = 'image is empty'; return undef; }
1778 return i_img_getmask($self->{IMG});
1786 if (!defined($self->{IMG})) { $self->{ERRSTR} = 'image is empty'; return undef; }
1787 i_img_setmask( $self->{IMG} , $opts{mask} );
1790 # Get number of colors in an image
1794 my %opts=(maxcolors=>2**30,@_);
1795 if (!defined($self->{IMG})) { $self->{ERRSTR}='image is empty'; return undef; }
1796 my $rc=i_count_colors($self->{IMG},$opts{'maxcolors'});
1797 return ($rc==-1? undef : $rc);
1800 # draw string to an image
1804 unless ($self->{IMG}) { $self->{ERRSTR}='empty input image'; return undef; }
1806 my %input=('x'=>0, 'y'=>0, @_);
1807 $input{string}||=$input{text};
1809 unless(exists $input{string}) {
1810 $self->{ERRSTR}="missing required parameter 'string'";
1814 unless($input{font}) {
1815 $self->{ERRSTR}="missing required parameter 'font'";
1819 unless ($input{font}->draw(image=>$self, %input)) {
1820 $self->{ERRSTR} = $self->_error_as_msg();
1827 # Shortcuts that can be exported
1829 sub newcolor { Imager::Color->new(@_); }
1830 sub newfont { Imager::Font->new(@_); }
1832 *NC=*newcolour=*newcolor;
1839 #### Utility routines
1842 ref $_[0] ? $_[0]->{ERRSTR} : $ERRSTR
1845 # Default guess for the type of an image from extension
1847 sub def_guess_type {
1850 $ext=($name =~ m/\.([^\.]+)$/)[0];
1851 return 'tiff' if ($ext =~ m/^tiff?$/);
1852 return 'jpeg' if ($ext =~ m/^jpe?g$/);
1853 return 'pnm' if ($ext =~ m/^p[pgb]m$/);
1854 return 'png' if ($ext eq "png");
1855 return 'gif' if ($ext eq "gif");
1859 # get the minimum of a list
1863 for(@_) { if ($_<$mx) { $mx=$_; }}
1867 # get the maximum of a list
1871 for(@_) { if ($_>$mx) { $mx=$_; }}
1875 # string stuff for iptc headers
1879 $str = substr($str,3);
1880 $str =~ s/[\n\r]//g;
1887 # A little hack to parse iptc headers.
1892 my($caption,$photogr,$headln,$credit);
1894 my $str=$self->{IPTCRAW};
1898 @ar=split(/8BIM/,$str);
1903 @sar=split(/\034\002/);
1904 foreach $item (@sar) {
1905 if ($item =~ m/^x/) {
1906 $caption=&clean($item);
1909 if ($item =~ m/^P/) {
1910 $photogr=&clean($item);
1913 if ($item =~ m/^i/) {
1914 $headln=&clean($item);
1917 if ($item =~ m/^n/) {
1918 $credit=&clean($item);
1924 return (caption=>$caption,photogr=>$photogr,headln=>$headln,credit=>$credit);
1927 # Autoload methods go after =cut, and are processed by the autosplit program.
1931 # Below is the stub of documentation for your module. You better edit it!
1935 Imager - Perl extension for Generating 24 bit Images
1939 use Imager qw(init);
1942 $img = Imager->new();
1943 $img->open(file=>'image.ppm',type=>'pnm')
1944 || print "failed: ",$img->{ERRSTR},"\n";
1945 $scaled=$img->scale(xpixels=>400,ypixels=>400);
1946 $scaled->write(file=>'sc_image.ppm',type=>'pnm')
1947 || print "failed: ",$scaled->{ERRSTR},"\n";
1951 Imager is a module for creating and altering images - It is not meant
1952 as a replacement or a competitor to ImageMagick or GD. Both are
1953 excellent packages and well supported.
1957 Almost all functions take the parameters in the hash fashion.
1960 $img->open(file=>'lena.png',type=>'png');
1964 $img->open(file=>'lena.png');
1966 =head2 Basic concept
1968 An Image object is created with C<$img = Imager-E<gt>new()> Should
1969 this fail for some reason an explanation can be found in
1970 C<$Imager::ERRSTR> usually error messages are stored in
1971 C<$img-E<gt>{ERRSTR}>, but since no object is created this is the only
1972 way to give back errors. C<$Imager::ERRSTR> is also used to report
1973 all errors not directly associated with an image object. Examples:
1975 $img=Imager->new(); # This is an empty image (size is 0 by 0)
1976 $img->open(file=>'lena.png',type=>'png'); # initializes from file
1978 or if you want to create an empty image:
1980 $img=Imager->new(xsize=>400,ysize=>300,channels=>4);
1982 This example creates a completely black image of width 400 and
1983 height 300 and 4 channels.
1985 If you have an existing image, use img_set() to change it's dimensions
1986 - this will destroy any existing image data:
1988 $img->img_set(xsize=>500, ysize=>500, channels=>4);
1990 To create paletted images, set the 'type' parameter to 'paletted':
1992 $img = Imager->new(xsize=>200, ysize=>200, channels=>3, type=>'paletted');
1994 which creates an image with a maxiumum of 256 colors, which you can
1995 change by supplying the C<maxcolors> parameter.
1997 You can create a new paletted image from an existing image using the
1998 to_paletted() method:
2000 $palimg = $img->to_paletted(\%opts)
2002 where %opts contains the options specified under L<Quantization options>.
2004 You can convert a paletted image (or any image) to an 8-bit/channel
2007 $rgbimg = $img->to_rgb8;
2009 Warning: if you draw on a paletted image with colors that aren't in
2010 the palette, the image will be internally converted to a normal image.
2012 For improved color precision you can use the bits parameter to specify
2013 16 bites per channel:
2015 $img = Imager->new(xsize=>200, ysize=>200, channels=>3, bits=>16);
2017 Note that as of this writing all functions should work on 16-bit
2018 images, but at only 8-bit/channel precision.
2020 Currently only 8 and 16/bit per channel image types are available,
2021 this may change later.
2023 Color objects are created by calling the Imager::Color->new()
2026 $color = Imager::Color->new($red, $green, $blue);
2027 $color = Imager::Color->new($red, $green, $blue, $alpha);
2028 $color = Imager::Color->new("#C0C0FF"); # html color specification
2030 This object can then be passed to functions that require a color parameter.
2032 Coordinates in Imager have the origin in the upper left corner. The
2033 horizontal coordinate increases to the right and the vertical
2036 =head2 Reading and writing images
2038 C<$img-E<gt>read()> generally takes two parameters, 'file' and 'type'.
2039 If the type of the file can be determined from the suffix of the file
2040 it can be omitted. Format dependant parameters are: For images of
2041 type 'raw' two extra parameters are needed 'xsize' and 'ysize', if the
2042 'channel' parameter is omitted for type 'raw' it is assumed to be 3.
2043 gif and png images might have a palette are converted to truecolor bit
2044 when read. Alpha channel is preserved for png images irregardless of
2045 them being in RGB or gray colorspace. Similarly grayscale jpegs are
2046 one channel images after reading them. For jpeg images the iptc
2047 header information (stored in the APP13 header) is avaliable to some
2048 degree. You can get the raw header with C<$img-E<gt>{IPTCRAW}>, but
2049 you can also retrieve the most basic information with
2050 C<%hsh=$img-E<gt>parseiptc()> as always patches are welcome. pnm has no
2051 extra options. Examples:
2053 $img = Imager->new();
2054 $img->read(file=>"cover.jpg") or die $img->errstr; # gets type from name
2056 $img = Imager->new();
2057 { local(*FH,$/); open(FH,"file.gif") or die $!; $a=<FH>; }
2058 $img->read(data=>$a,type=>'gif') or die $img->errstr;
2060 The second example shows how to read an image from a scalar, this is
2061 usefull if your data originates from somewhere else than a filesystem
2062 such as a database over a DBI connection.
2064 When writing to a tiff image file you can also specify the 'class'
2065 parameter, which can currently take a single value, "fax". If class
2066 is set to fax then a tiff image which should be suitable for faxing
2067 will be written. For the best results start with a grayscale image.
2068 By default the image is written at fine resolution you can override
2069 this by setting the "fax_fine" parameter to 0.
2071 If you are reading from a gif image file, you can supply a 'colors'
2072 parameter which must be a reference to a scalar. The referenced
2073 scalar will receive an array reference which contains the colors, each
2074 represented as an Imager::Color object.
2076 If you already have an open file handle, for example a socket or a
2077 pipe, you can specify the 'fd' parameter instead of supplying a
2078 filename. Please be aware that you need to use fileno() to retrieve
2079 the file descriptor for the file:
2081 $img->read(fd=>fileno(FILE), type=>'gif') or die $img->errstr;
2083 For writing using the 'fd' option you will probably want to set $| for
2084 that descriptor, since the writes to the file descriptor bypass Perl's
2085 (or the C libraries) buffering. Setting $| should avoid out of order
2088 *Note that load() is now an alias for read but will be removed later*
2090 C<$img-E<gt>write> has the same interface as C<read()>. The earlier
2091 comments on C<read()> for autodetecting filetypes apply. For jpegs
2092 quality can be adjusted via the 'jpegquality' parameter (0-100). The
2093 number of colorplanes in gifs are set with 'gifplanes' and should be
2094 between 1 (2 color) and 8 (256 colors). It is also possible to choose
2095 between two quantizing methods with the parameter 'gifquant'. If set
2096 to mc it uses the mediancut algorithm from either giflibrary. If set
2097 to lm it uses a local means algorithm. It is then possible to give
2098 some extra settings. lmdither is the dither deviation amount in pixels
2099 (manhattan distance). lmfixed can be an array ref who holds an array
2100 of Imager::Color objects. Note that the local means algorithm needs
2101 much more cpu time but also gives considerable better results than the
2102 median cut algorithm.
2104 Currently just for gif files, you can specify various options for the
2105 conversion from Imager's internal RGB format to the target's indexed
2106 file format. If you set the gifquant option to 'gen', you can use the
2107 options specified under L<Quantization options>.
2109 To see what Imager is compiled to support the following code snippet
2113 print "@{[keys %Imager::formats]}";
2115 When reading raw images you need to supply the width and height of the
2116 image in the xsize and ysize options:
2118 $img->read(file=>'foo.raw', xsize=>100, ysize=>100)
2119 or die "Cannot read raw image\n";
2121 If your input file has more channels than you want, or (as is common),
2122 junk in the fourth channel, you can use the datachannels and
2123 storechannels options to control the number of channels in your input
2124 file and the resulting channels in your image. For example, if your
2125 input image uses 32-bits per pixel with red, green, blue and junk
2126 values for each pixel you could do:
2128 $img->read(file=>'foo.raw', xsize=>100, ysize=>100, datachannels=>4,
2130 or die "Cannot read raw image\n";
2132 Normally the raw image is expected to have the value for channel 1
2133 immediately following channel 0 and channel 2 immediately following
2134 channel 1 for each pixel. If your input image has all the channel 0
2135 values for the first line of the image, followed by all the channel 1
2136 values for the first line and so on, you can use the interleave option:
2138 $img->read(file=>'foo.raw', xsize=100, ysize=>100, interleave=>1)
2139 or die "Cannot read raw image\n";
2141 =head2 Multi-image files
2143 Currently just for gif files, you can create files that contain more
2148 Imager->write_multi(\%opts, @images)
2150 Where %opts describes 4 possible types of outputs:
2156 This is C<gif> for gif animations.
2160 A code reference which is called with a single parameter, the data to
2161 be written. You can also specify $opts{maxbuffer} which is the
2162 maximum amount of data buffered. Note that there can be larger writes
2163 than this if the file library writes larger blocks. A smaller value
2164 maybe useful for writing to a socket for incremental display.
2168 The file descriptor to save the images to.
2172 The name of the file to write to.
2174 %opts may also include the keys from L<Gif options> and L<Quantization
2179 You must also specify the file format using the 'type' option.
2181 The current aim is to support other multiple image formats in the
2182 future, such as TIFF, and to support reading multiple images from a
2188 # ... code to put images in @images
2189 Imager->write_multi({type=>'gif',
2191 gif_delays=>[ (10) x @images ] },
2195 You can read multi-image files (currently only GIF files) using the
2196 read_multi() method:
2198 my @imgs = Imager->read_multi(file=>'foo.gif')
2199 or die "Cannot read images: ",Imager->errstr;
2201 The possible parameters for read_multi() are:
2207 The name of the file to read in.
2211 A filehandle to read in. This can be the name of a filehandle, but it
2212 will need the package name, no attempt is currently made to adjust
2213 this to the caller's package.
2217 The numeric file descriptor of an open file (or socket).
2221 A function to be called to read in data, eg. reading a blob from a
2222 database incrementally.
2226 The data of the input file in memory.
2230 The type of file. If the file is parameter is given and provides
2231 enough information to guess the type, then this parameter is optional.
2235 Note: you cannot use the callback or data parameter with giflib
2236 versions before 4.0.
2238 When reading from a GIF file with read_multi() the images are returned
2243 These options can be specified when calling write_multi() for gif
2244 files, when writing a single image with the gifquant option set to
2245 'gen', or for direct calls to i_writegif_gen and i_writegif_callback.
2247 Note that some viewers will ignore some of these options
2248 (gif_user_input in particular).
2252 =item gif_each_palette
2254 Each image in the gif file has it's own palette if this is non-zero.
2255 All but the first image has a local colour table (the first uses the
2256 global colour table.
2260 The images are written interlaced if this is non-zero.
2264 A reference to an array containing the delays between images, in 1/100
2267 If you want the same delay for every frame you can simply set this to
2268 the delay in 1/100 seconds.
2270 =item gif_user_input
2272 A reference to an array contains user input flags. If the given flag
2273 is non-zero the image viewer should wait for input before displaying
2278 A reference to an array of image disposal methods. These define what
2279 should be done to the image before displaying the next one. These are
2280 integers, where 0 means unspecified, 1 means the image should be left
2281 in place, 2 means restore to background colour and 3 means restore to
2284 =item gif_tran_color
2286 A reference to an Imager::Color object, which is the colour to use for
2287 the palette entry used to represent transparency in the palette. You
2288 need to set the transp option (see L<Quantization options>) for this
2293 A reference to an array of references to arrays which represent screen
2294 positions for each image.
2296 =item gif_loop_count
2298 If this is non-zero the Netscape loop extension block is generated,
2299 which makes the animation of the images repeat.
2301 This is currently unimplemented due to some limitations in giflib.
2305 =head2 Quantization options
2307 These options can be specified when calling write_multi() for gif
2308 files, when writing a single image with the gifquant option set to
2309 'gen', or for direct calls to i_writegif_gen and i_writegif_callback.
2315 A arrayref of colors that are fixed. Note that some color generators
2320 The type of transparency processing to perform for images with an
2321 alpha channel where the output format does not have a proper alpha
2322 channel (eg. gif). This can be any of:
2328 No transparency processing is done. (default)
2332 Pixels more transparent that tr_threshold are rendered as transparent.
2336 An error diffusion dither is done on the alpha channel. Note that
2337 this is independent of the translation performed on the colour
2338 channels, so some combinations may cause undesired artifacts.
2342 The ordered dither specified by tr_orddith is performed on the alpha
2347 This will only be used if the image has an alpha channel, and if there
2348 is space in the palette for a transparency colour.
2352 The highest alpha value at which a pixel will be made transparent when
2353 transp is 'threshold'. (0-255, default 127)
2357 The type of error diffusion to perform on the alpha channel when
2358 transp is 'errdiff'. This can be any defined error diffusion type
2359 except for custom (see errdiff below).
2363 The type of ordered dither to perform on the alpha channel when transp
2364 is 'ordered'. Possible values are:
2370 A semi-random map is used. The map is the same each time.
2382 horizontal line dither.
2386 vertical line dither.
2392 diagonal line dither
2398 diagonal line dither
2402 dot matrix dither (currently the default). This is probably the best
2403 for displays (like web pages).
2407 A custom dither matrix is used - see tr_map
2413 When tr_orddith is custom this defines an 8 x 8 matrix of integers
2414 representing the transparency threshold for pixels corresponding to
2415 each position. This should be a 64 element array where the first 8
2416 entries correspond to the first row of the matrix. Values should be
2421 Defines how the quantization engine will build the palette(s).
2422 Currently this is ignored if 'translate' is 'giflib', but that may
2423 change. Possible values are:
2429 Only colors supplied in 'colors' are used.
2433 The web color map is used (need url here.)
2437 The original code for generating the color map (Addi's code) is used.
2441 Other methods may be added in the future.
2445 A arrayref containing Imager::Color objects, which represents the
2446 starting set of colors to use in translating the images. webmap will
2447 ignore this. The final colors used are copied back into this array
2448 (which is expanded if necessary.)
2452 The maximum number of colors to use in the image.
2456 The method used to translate the RGB values in the source image into
2457 the colors selected by make_colors. Note that make_colors is ignored
2458 whene translate is 'giflib'.
2460 Possible values are:
2466 The giflib native quantization function is used.
2470 The closest color available is used.
2474 The pixel color is modified by perturb, and the closest color is chosen.
2478 An error diffusion dither is performed.
2482 It's possible other transate values will be added.
2486 The type of error diffusion dither to perform. These values (except
2487 for custom) can also be used in tr_errdif.
2493 Floyd-Steinberg dither
2497 Jarvis, Judice and Ninke dither
2505 Custom. If you use this you must also set errdiff_width,
2506 errdiff_height and errdiff_map.
2512 =item errdiff_height
2518 When translate is 'errdiff' and errdiff is 'custom' these define a
2519 custom error diffusion map. errdiff_width and errdiff_height define
2520 the size of the map in the arrayref in errdiff_map. errdiff_orig is
2521 an integer which indicates the current pixel position in the top row
2526 When translate is 'perturb' this is the magnitude of the random bias
2527 applied to each channel of the pixel before it is looked up in the
2532 =head2 Obtaining/setting attributes of images
2534 To get the size of an image in pixels the C<$img-E<gt>getwidth()> and
2535 C<$img-E<gt>getheight()> are used.
2537 To get the number of channels in
2538 an image C<$img-E<gt>getchannels()> is used. $img-E<gt>getmask() and
2539 $img-E<gt>setmask() are used to get/set the channel mask of the image.
2541 $mask=$img->getmask();
2542 $img->setmask(mask=>1+2); # modify red and green only
2543 $img->setmask(mask=>8); # modify alpha only
2544 $img->setmask(mask=>$mask); # restore previous mask
2546 The mask of an image describes which channels are updated when some
2547 operation is performed on an image. Naturally it is not possible to
2548 apply masks to operations like scaling that alter the dimensions of
2551 It is possible to have Imager find the number of colors in an image
2552 by using C<$img-E<gt>getcolorcount()>. It requires memory proportionally
2553 to the number of colors in the image so it is possible to have it
2554 stop sooner if you only need to know if there are more than a certain number
2555 of colors in the image. If there are more colors than asked for
2556 the function return undef. Examples:
2558 if (!defined($img->getcolorcount(maxcolors=>512)) {
2559 print "Less than 512 colors in image\n";
2562 The bits() method retrieves the number of bits used to represent each
2563 channel in a pixel, typically 8. The type() method returns either
2564 'direct' for truecolor images or 'paletted' for paletted images. The
2565 virtual() method returns non-zero if the image contains no actual
2566 pixels, for example masked images.
2568 =head2 Paletted Images
2570 In general you can work with paletted images in the same way as RGB
2571 images, except that if you attempt to draw to a paletted image with a
2572 color that is not in the image's palette, the image will be converted
2573 to an RGB image. This means that drawing on a paletted image with
2574 anti-aliasing enabled will almost certainly convert the image to RGB.
2576 You can add colors to a paletted image with the addcolors() method:
2578 my @colors = ( Imager::Color->new(255, 0, 0),
2579 Imager::Color->new(0, 255, 0) );
2580 my $index = $img->addcolors(colors=>\@colors);
2582 The return value is the index of the first color added, or undef if
2583 adding the colors would overflow the palette.
2585 Once you have colors in the palette you can overwrite them with the
2588 $img->setcolors(start=>$start, colors=>\@colors);
2590 Returns true on success.
2592 To retrieve existing colors from the palette use the getcolors() method:
2594 # get the whole palette
2595 my @colors = $img->getcolors();
2596 # get a single color
2597 my $color = $img->getcolors(start=>$index);
2598 # get a range of colors
2599 my @colors = $img->getcolors(start=>$index, count=>$count);
2601 To quickly find a color in the palette use findcolor():
2603 my $index = $img->findcolor(color=>$color);
2605 which returns undef on failure, or the index of the color.
2607 You can get the current palette size with $img->colorcount, and the
2608 maximum size of the palette with $img->maxcolors.
2610 =head2 Drawing Methods
2612 IMPLEMENTATION MORE OR LESS DONE CHECK THE TESTS
2613 DOCUMENTATION OF THIS SECTION OUT OF SYNC
2615 It is possible to draw with graphics primitives onto images. Such
2616 primitives include boxes, arcs, circles and lines. A reference
2617 oriented list follows.
2620 $img->box(color=>$blue,xmin=>10,ymin=>30,xmax=>200,ymax=>300,filled=>1);
2622 The above example calls the C<box> method for the image and the box
2623 covers the pixels with in the rectangle specified. If C<filled> is
2624 ommited it is drawn as an outline. If any of the edges of the box are
2625 ommited it will snap to the outer edge of the image in that direction.
2626 Also if a color is omitted a color with (255,255,255,255) is used
2630 $img->arc(color=>$red, r=20, x=>200, y=>100, d1=>10, d2=>20 );
2632 This creates a filled red arc with a 'center' at (200, 100) and spans
2633 10 degrees and the slice has a radius of 20. SEE section on BUGS.
2636 $img->circle(color=>$green, r=50, x=>200, y=>100);
2638 This creates a green circle with its center at (200, 100) and has a
2642 $img->line(color=>$green, x1=10, x2=>100,
2643 y1=>20, y2=>50, antialias=>1 );
2645 That draws an antialiased line from (10,100) to (20,50).
2648 $img->polyline(points=>[[$x0,$y0],[$x1,$y1],[$x2,$y2]],color=>$red);
2649 $img->polyline(x=>[$x0,$x1,$x2], y=>[$y0,$y1,$y2], antialias=>1);
2651 Polyline is used to draw multilple lines between a series of points.
2652 The point set can either be specified as an arrayref to an array of
2653 array references (where each such array represents a point). The
2654 other way is to specify two array references.
2656 =head2 Text rendering
2658 Text rendering is described in the Imager::Font manpage.
2660 =head2 Image resizing
2662 To scale an image so porportions are maintained use the
2663 C<$img-E<gt>scale()> method. if you give either a xpixels or ypixels
2664 parameter they will determine the width or height respectively. If
2665 both are given the one resulting in a larger image is used. example:
2666 C<$img> is 700 pixels wide and 500 pixels tall.
2668 $img->scale(xpixels=>400); # 400x285
2669 $img->scale(ypixels=>400); # 560x400
2671 $img->scale(xpixels=>400,ypixels=>400); # 560x400
2672 $img->scale(xpixels=>400,ypixels=>400,type=>min); # 400x285
2674 $img->scale(scalefactor=>0.25); 175x125 $img->scale(); # 350x250
2676 if you want to create low quality previews of images you can pass
2677 C<qtype=E<gt>'preview'> to scale and it will use nearest neighbor
2678 sampling instead of filtering. It is much faster but also generates
2679 worse looking images - especially if the original has a lot of sharp
2680 variations and the scaled image is by more than 3-5 times smaller than
2683 If you need to scale images per axis it is best to do it simply by
2684 calling scaleX and scaleY. You can pass either 'scalefactor' or
2685 'pixels' to both functions.
2687 Another way to resize an image size is to crop it. The parameters
2688 to crop are the edges of the area that you want in the returned image.
2689 If a parameter is omited a default is used instead.
2691 $newimg = $img->crop(left=>50, right=>100, top=>10, bottom=>100);
2692 $newimg = $img->crop(left=>50, top=>10, width=>50, height=>90);
2693 $newimg = $img->crop(left=>50, right=>100); # top
2695 You can also specify width and height parameters which will produce a
2696 new image cropped from the center of the input image, with the given
2699 $newimg = $img->crop(width=>50, height=>50);
2701 The width and height parameters take precedence over the left/right
2702 and top/bottom parameters respectively.
2704 =head2 Copying images
2706 To create a copy of an image use the C<copy()> method. This is usefull
2707 if you want to keep an original after doing something that changes the image
2708 inplace like writing text.
2712 To copy an image to onto another image use the C<paste()> method.
2714 $dest->paste(left=>40,top=>20,img=>$logo);
2716 That copies the entire C<$logo> image onto the C<$dest> image so that the
2717 upper left corner of the C<$logo> image is at (40,20).
2720 =head2 Flipping images
2722 An inplace horizontal or vertical flip is possible by calling the
2723 C<flip()> method. If the original is to be preserved it's possible to
2724 make a copy first. The only parameter it takes is the C<dir>
2725 parameter which can take the values C<h>, C<v>, C<vh> and C<hv>.
2727 $img->flip(dir=>"h"); # horizontal flip
2728 $img->flip(dir=>"vh"); # vertical and horizontal flip
2729 $nimg = $img->copy->flip(dir=>"v"); # make a copy and flip it vertically
2731 =head2 Rotating images
2733 Use the rotate() method to rotate an image.
2735 To rotate by an exact amount in degrees or radians, use the 'degrees'
2736 or 'radians' parameter:
2738 my $rot20 = $img->rotate(degrees=>20);
2739 my $rotpi4 = $img->rotate(radians=>3.14159265/4);
2741 To rotate in steps of 90 degrees, use the 'right' parameter:
2743 my $rotated = $img->rotate(right=>270);
2745 Rotations are clockwise for positive values.
2747 =head2 Blending Images
2749 To put an image or a part of an image directly
2750 into another it is best to call the C<paste()> method on the image you
2753 $img->paste(img=>$srcimage,left=>30,top=>50);
2755 That will take paste C<$srcimage> into C<$img> with the upper
2756 left corner at (30,50). If no values are given for C<left>
2757 or C<top> they will default to 0.
2759 A more complicated way of blending images is where one image is
2760 put 'over' the other with a certain amount of opaqueness. The
2761 method that does this is rubthrough.
2763 $img->rubthrough(src=>$srcimage,tx=>30,ty=>50);
2765 That will take the image C<$srcimage> and overlay it with the upper
2766 left corner at (30,50). You can rub 2 or 4 channel images onto a 3
2767 channel image, or a 2 channel image onto a 1 channel image. The last
2768 channel is used as an alpha channel.
2773 A special image method is the filter method. An example is:
2775 $img->filter(type=>'autolevels');
2777 This will call the autolevels filter. Here is a list of the filters
2778 that are always avaliable in Imager. This list can be obtained by
2779 running the C<filterlist.perl> script that comes with the module
2783 autolevels lsat(0.1) usat(0.1) skew(0)
2787 gradgen xo yo colors dist
2789 noise amount(3) subtype(0)
2790 radnoise xo(100) yo(100) ascale(17.0) rscale(0.02)
2791 turbnoise xo(0.0) yo(0.0) scale(10.0)
2793 The default values are in parenthesis. All parameters must have some
2794 value but if a parameter has a default value it may be omitted when
2795 calling the filter function.
2803 scales the value of each channel so that the values in the image will
2804 cover the whole possible range for the channel. I<lsat> and I<usat>
2805 truncate the range by the specified fraction at the top and bottom of
2806 the range respectivly..
2810 scales each channel by I<intensity>. Values of I<intensity> < 1.0
2811 will reduce the contrast.
2815 performs 2 1-dimensional convolutions on the image using the values
2816 from I<coef>. I<coef> should be have an odd length.
2820 performs a gaussian blur of the image, using I<stddev> as the standard
2821 deviation of the curve used to combine pixels, larger values give
2822 bigger blurs. For a definition of Gaussian Blur, see:
2824 http://www.maths.abdn.ac.uk/~igc/tch/mx4002/notes/node99.html
2828 renders a gradient, with the given I<colors> at the corresponding
2829 points (x,y) in I<xo> and I<yo>. You can specify the way distance is
2830 measured for color blendeing by setting I<dist> to 0 for Euclidean, 1
2831 for Euclidean squared, and 2 for Manhattan distance.
2835 inverts the image, black to white, white to black. All channels are
2836 inverted, including the alpha channel if any.
2840 adds noise of the given I<amount> to the image. If I<subtype> is
2841 zero, the noise is even to each channel, otherwise noise is added to
2842 each channel independently.
2846 renders radiant Perlin turbulent noise. The centre of the noise is at
2847 (I<xo>, I<yo>), I<ascale> controls the angular scale of the noise ,
2848 and I<rscale> the radial scale, higher numbers give more detail.
2852 renders Perlin turbulent noise. (I<xo>, I<yo>) controls the origin of
2853 the noise, and I<scale> the scale of the noise, with lower numbers
2858 A demonstration of the the filters can be found at:
2860 http://www.develop-help.com/imager/filters.html
2862 (This is a slow link.)
2864 =head2 Color transformations
2866 You can use the convert method to transform the color space of an
2867 image using a matrix. For ease of use some presets are provided.
2869 The convert method can be used to:
2875 convert an RGB or RGBA image to grayscale.
2879 convert a grayscale image to RGB.
2883 extract a single channel from an image.
2887 set a given channel to a particular value (or from another channel)
2891 The currently defined presets are:
2899 converts an RGBA image into a grayscale image with alpha channel, or
2900 an RGB image into a grayscale image without an alpha channel.
2902 This weights the RGB channels at 22.2%, 70.7% and 7.1% respectively.
2906 removes the alpha channel from a 2 or 4 channel image. An identity
2913 extracts the first channel of the image into a single channel image
2919 extracts the second channel of the image into a single channel image
2925 extracts the third channel of the image into a single channel image
2929 extracts the alpha channel of the image into a single channel image.
2931 If the image has 1 or 3 channels (assumed to be grayscale of RGB) then
2932 the resulting image will be all white.
2936 converts a grayscale image to RGB, preserving the alpha channel if any
2940 adds an alpha channel to a grayscale or RGB image. Preserves an
2941 existing alpha channel for a 2 or 4 channel image.
2945 For example, to convert an RGB image into a greyscale image:
2947 $new = $img->convert(preset=>'grey'); # or gray
2949 or to convert a grayscale image to an RGB image:
2951 $new = $img->convert(preset=>'rgb');
2953 The presets aren't necessary simple constants in the code, some are
2954 generated based on the number of channels in the input image.
2956 If you want to perform some other colour transformation, you can use
2957 the 'matrix' parameter.
2959 For each output pixel the following matrix multiplication is done:
2961 channel[0] [ [ $c00, $c01, ... ] inchannel[0]
2962 [ ... ] = ... x [ ... ]
2963 channel[n-1] [ $cn0, ..., $cnn ] ] inchannel[max]
2966 So if you want to swap the red and green channels on a 3 channel image:
2968 $new = $img->convert(matrix=>[ [ 0, 1, 0 ],
2972 or to convert a 3 channel image to greyscale using equal weightings:
2974 $new = $img->convert(matrix=>[ [ 0.333, 0.333, 0.334 ] ])
2976 =head2 Color Mappings
2978 You can use the map method to map the values of each channel of an
2979 image independently using a list of lookup tables. It's important to
2980 realize that the modification is made inplace. The function simply
2981 returns the input image again or undef on failure.
2983 Each channel is mapped independently through a lookup table with 256
2984 entries. The elements in the table should not be less than 0 and not
2985 greater than 255. If they are out of the 0..255 range they are
2986 clamped to the range. If a table does not contain 256 entries it is
2989 Single channels can mapped by specifying their name and the mapping
2990 table. The channel names are C<red>, C<green>, C<blue>, C<alpha>.
2992 @map = map { int( $_/2 } 0..255;
2993 $img->map( red=>\@map );
2995 It is also possible to specify a single map that is applied to all
2996 channels, alpha channel included. For example this applies a gamma
2997 correction with a gamma of 1.4 to the input image.
3000 @map = map { int( 0.5 + 255*($_/255)**$gamma ) } 0..255;
3001 $img->map(all=> \@map);
3003 The C<all> map is used as a default channel, if no other map is
3004 specified for a channel then the C<all> map is used instead. If we
3005 had not wanted to apply gamma to the alpha channel we would have used:
3007 $img->map(all=> \@map, alpha=>[]);
3009 Since C<[]> contains fewer than 256 element the gamma channel is
3012 It is also possible to simply specify an array of maps that are
3013 applied to the images in the rgba order. For example to apply
3014 maps to the C<red> and C<blue> channels one would use:
3016 $img->map(maps=>[\@redmap, [], \@bluemap]);
3020 =head2 Transformations
3022 Another special image method is transform. It can be used to generate
3023 warps and rotations and such features. It can be given the operations
3024 in postfix notation or the module Affix::Infix2Postfix can be used.
3025 Look in the test case t/t55trans.t for an example.
3027 transform() needs expressions (or opcodes) that determine the source
3028 pixel for each target pixel. Source expressions are infix expressions
3029 using any of the +, -, *, / or ** binary operators, the - unary
3030 operator, ( and ) for grouping and the sin() and cos() functions. The
3031 target pixel is input as the variables x and y.
3033 You specify the x and y expressions as xexpr and yexpr respectively.
3034 You can also specify opcodes directly, but that's magic deep enough
3035 that you can look at the source code.
3037 You can still use the transform() function, but the transform2()
3038 function is just as fast and is more likely to be enhanced and
3041 Later versions of Imager also support a transform2() class method
3042 which allows you perform a more general set of operations, rather than
3043 just specifying a spatial transformation as with the transform()
3044 method, you can also perform colour transformations, image synthesis
3045 and image combinations.
3047 transform2() takes an reference to an options hash, and a list of
3048 images to operate one (this list may be empty):
3053 my $img = Imager::transform2(\%opts, @imgs)
3054 or die "transform2 failed: $Imager::ERRSTR";
3056 The options hash may define a transformation function, and optionally:
3062 width - the width of the image in pixels. If this isn't supplied the
3063 width of the first input image is used. If there are no input images
3068 height - the height of the image in pixels. If this isn't supplied
3069 the height of the first input image is used. If there are no input
3070 images an error occurs.
3074 constants - a reference to hash of constants to define for the
3075 expression engine. Some extra constants are defined by Imager
3079 The tranformation function is specified using either the expr or
3080 rpnexpr member of the options.
3084 =item Infix expressions
3086 You can supply infix expressions to transform 2 with the expr keyword.
3088 $opts{expr} = 'return getp1(w-x, h-y)'
3090 The 'expression' supplied follows this general grammar:
3092 ( identifier '=' expr ';' )* 'return' expr
3094 This allows you to simplify your expressions using variables.
3096 A more complex example might be:
3098 $opts{expr} = 'pix = getp1(x,y); return if(value(pix)>0.8,pix*0.8,pix)'
3100 Currently to use infix expressions you must have the Parse::RecDescent
3101 module installed (available from CPAN). There is also what might be a
3102 significant delay the first time you run the infix expression parser
3103 due to the compilation of the expression grammar.
3105 =item Postfix expressions
3107 You can supply postfix or reverse-polish notation expressions to
3108 transform2() through the rpnexpr keyword.
3110 The parser for rpnexpr emulates a stack machine, so operators will
3111 expect to see their parameters on top of the stack. A stack machine
3112 isn't actually used during the image transformation itself.
3114 You can store the value at the top of the stack in a variable called
3115 foo using !foo and retrieve that value again using @foo. The !foo
3116 notation will pop the value from the stack.
3118 An example equivalent to the infix expression above:
3120 $opts{rpnexpr} = 'x y getp1 !pix @pix value 0.8 gt @pix 0.8 * @pix ifp'
3124 transform2() has a fairly rich range of operators.
3128 =item +, *, -, /, %, **
3130 multiplication, addition, subtraction, division, remainder and
3131 exponentiation. Multiplication, addition and subtraction can be used
3132 on colour values too - though you need to be careful - adding 2 white
3133 values together and multiplying by 0.5 will give you grey, not white.
3135 Division by zero (or a small number) just results in a large number.
3136 Modulo zero (or a small number) results in zero.
3138 =item sin(N), cos(N), atan2(y,x)
3140 Some basic trig functions. They work in radians, so you can't just
3143 =item distance(x1, y1, x2, y2)
3145 Find the distance between two points. This is handy (along with
3146 atan2()) for producing circular effects.
3150 Find the square root. I haven't had much use for this since adding
3151 the distance() function.
3155 Find the absolute value.
3157 =item getp1(x,y), getp2(x,y), getp3(x, y)
3159 Get the pixel at position (x,y) from the first, second or third image
3160 respectively. I may add a getpn() function at some point, but this
3161 prevents static checking of the instructions against the number of
3162 images actually passed in.
3164 =item value(c), hue(c), sat(c), hsv(h,s,v)
3166 Separates a colour value into it's value (brightness), hue (colour)
3167 and saturation elements. Use hsv() to put them back together (after
3168 suitable manipulation).
3170 =item red(c), green(c), blue(c), rgb(r,g,b)
3172 Separates a colour value into it's red, green and blue colours. Use
3173 rgb(r,g,b) to put it back together.
3177 Convert a value to an integer. Uses a C int cast, so it may break on
3180 =item if(cond,ntrue,nfalse), if(cond,ctrue,cfalse)
3182 A simple (and inefficient) if function.
3184 =item <=,<,==,>=,>,!=
3186 Relational operators (typically used with if()). Since we're working
3187 with floating point values the equalities are 'near equalities' - an
3188 epsilon value is used.
3190 =item &&, ||, not(n)
3192 Basic logical operators.
3200 =item rpnexpr=>'x 25 % 15 * y 35 % 10 * getp1 !pat x y getp1 !pix @pix sat 0.7 gt @pat @pix ifp'
3202 tiles a smaller version of the input image over itself where the
3203 colour has a saturation over 0.7.
3205 =item rpnexpr=>'x 25 % 15 * y 35 % 10 * getp1 !pat y 360 / !rat x y getp1 1 @rat - pmult @pat @rat pmult padd'
3207 tiles the input image over itself so that at the top of the image the
3208 full-size image is at full strength and at the bottom the tiling is
3211 =item rpnexpr=>'x y getp1 !pix @pix value 0.96 gt @pix sat 0.1 lt and 128 128 255 rgb @pix ifp'
3213 replace pixels that are white or almost white with a palish blue
3215 =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'
3217 Tiles the input image overitself where the image isn't white or almost
3220 =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'
3224 =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'
3226 A spiral built on top of a colour wheel.
3230 For details on expression parsing see L<Imager::Expr>. For details on
3231 the virtual machine used to transform the images, see
3232 L<Imager::regmach.pod>.
3234 =head2 Matrix Transformations
3236 Rather than having to write code in a little language, you can use a
3237 matrix to perform transformations, using the matrix_transform()
3240 my $im2 = $im->matrix_transform(matrix=>[ -1, 0, $im->getwidth-1,
3244 By default the output image will be the same size as the input image,
3245 but you can supply the xsize and ysize parameters to change the size.
3247 Rather than building matrices by hand you can use the Imager::Matrix2d
3248 module to build the matrices. This class has methods to allow you to
3249 scale, shear, rotate, translate and reflect, and you can combine these
3250 with an overloaded multiplication operator.
3252 WARNING: the matrix you provide in the matrix operator transforms the
3253 co-ordinates within the B<destination> image to the co-ordinates
3254 within the I<source> image. This can be confusing.
3256 Since Imager has 3 different fairly general ways of transforming an
3257 image spatially, this method also has a yatf() alias. Yet Another
3258 Transformation Function.
3260 =head2 Masked Images
3262 Masked images let you control which pixels are modified in an
3263 underlying image. Where the first channel is completely black in the
3264 mask image, writes to the underlying image are ignored.
3266 For example, given a base image called $img:
3268 my $mask = Imager->new(xsize=>$img->getwidth, ysize=>getheight,
3270 # ... draw something on the mask
3271 my $maskedimg = $img->masked(mask=>$mask);
3273 You can specifiy the region of the underlying image that is masked
3274 using the left, top, right and bottom options.
3276 If you just want a subset of the image, without masking, just specify
3277 the region without specifying a mask.
3281 It is possible to add filters to the module without recompiling the
3282 module itself. This is done by using DSOs (Dynamic shared object)
3283 avaliable on most systems. This way you can maintain our own filters
3284 and not have to get me to add it, or worse patch every new version of
3285 the Module. Modules can be loaded AND UNLOADED at runtime. This
3286 means that you can have a server/daemon thingy that can do something
3289 load_plugin("dynfilt/dyntest.so") || die "unable to load plugin\n";
3290 %hsh=(a=>35,b=>200,type=>lin_stretch);
3292 unload_plugin("dynfilt/dyntest.so") || die "unable to load plugin\n";
3293 $img->write(type=>'pnm',file=>'testout/t60.jpg')
3294 || die "error in write()\n";
3296 Someone decides that the filter is not working as it should -
3297 dyntest.c modified and recompiled.
3299 load_plugin("dynfilt/dyntest.so") || die "unable to load plugin\n";
3302 An example plugin comes with the module - Please send feedback to
3303 addi@umich.edu if you test this.
3305 Note: This seems to test ok on the following systems:
3306 Linux, Solaris, HPUX, OpenBSD, FreeBSD, TRU64/OSF1, AIX.
3307 If you test this on other systems please let me know.
3311 Image tags contain meta-data about the image, ie. information not
3312 stored as pixels of the image.
3314 At the perl level each tag has a name or code and a value, which is an
3315 integer or an arbitrary string. An image can contain more than one
3316 tag with the same name or code.
3318 You can retrieve tags from an image using the tags() method, you can
3319 get all of the tags in an image, as a list of array references, with
3320 the code or name of the tag followed by the value of the tag:
3322 my @alltags = $img->tags;
3324 or you can get all tags that have a given name:
3326 my @namedtags = $img->tags(name=>$name);
3330 my @tags = $img->tags(code=>$code);
3332 You can add tags using the addtag() method, either by name:
3334 my $index = $img->addtag(name=>$name, value=>$value);
3338 my $index = $img->addtag(code=>$code, value=>$value);
3340 You can remove tags with the deltag() method, either by index:
3342 $img->deltag(index=>$index);
3346 $img->deltag(name=>$name);
3350 $img->deltag(code=>$code);
3352 In each case deltag() returns the number of tags deleted.
3354 When you read a GIF image using read_multi(), each image can include
3361 the offset of the image from the left of the "screen" ("Image Left
3366 the offset of the image from the top of the "screen" ("Image Top Position")
3370 non-zero if the image was interlaced ("Interlace Flag")
3372 =item gif_screen_width
3374 =item gif_screen_height
3376 the size of the logical screen ("Logical Screen Width",
3377 "Logical Screen Height")
3381 Non-zero if this image had a local color map.
3383 =item gif_background
3385 The index in the global colormap of the logical screen's background
3386 color. This is only set if the current image uses the global
3389 =item gif_trans_index
3391 The index of the color in the colormap used for transparency. If the
3392 image has a transparency then it is returned as a 4 channel image with
3393 the alpha set to zero in this palette entry. ("Transparent Color Index")
3397 The delay until the next frame is displayed, in 1/100 of a second.
3400 =item gif_user_input
3402 whether or not a user input is expected before continuing (view dependent)
3403 ("User Input Flag").
3407 how the next frame is displayed ("Disposal Method")
3411 the number of loops from the Netscape Loop extension. This may be zero.
3415 the first block of the first gif comment before each image.
3419 Where applicable, the ("name") is the name of that field from the GIF89
3422 The following ares are set in a TIFF image when read, and can be set
3427 =item tiff_resolutionunit
3429 The value of the ResolutionUnit tag. This is ignored on writing if
3430 the i_aspect_only tag is non-zero.
3434 Some standard tags will be implemented as time goes by:
3442 The spatial resolution of the image in pixels per inch. If the image
3443 format uses a different scale, eg. pixels per meter, then this value
3444 is converted. A floating point number stored as a string.
3448 If this is non-zero then the values in i_xres and i_yres are treated
3449 as a ratio only. If the image format does not support aspect ratios
3450 then this is scaled so the smaller value is 72dpi.
3456 box, arc, circle do not support antialiasing yet. arc, is only filled
3457 as of yet. Some routines do not return $self where they should. This
3458 affects code like this, C<$img-E<gt>box()-E<gt>arc()> where an object
3461 When saving Gif images the program does NOT try to shave of extra
3462 colors if it is possible. If you specify 128 colors and there are
3463 only 2 colors used - it will have a 128 colortable anyway.
3467 Arnar M. Hrafnkelsson, addi@umich.edu, and recently lots of assistance
3468 from Tony Cook. See the README for a complete list.
3472 perl(1), Imager::Color(3), Imager::Font(3), Imager::Matrix2d(3),
3473 Affix::Infix2Postfix(3), Parse::RecDescent(3)
3474 http://www.eecs.umich.edu/~addi/perl/Imager/