package Imager;
-
-
use strict;
-use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS %formats $DEBUG %filters %DSOs $ERRSTR $fontstate %OPCODES $I2P $FORMATGUESS);
+use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS %formats $DEBUG %filters %DSOs $ERRSTR $fontstate %OPCODES $I2P $FORMATGUESS $warn_obsolete);
use IO::File;
use Imager::Color;
DSO_close
DSO_funclist
DSO_call
-
+
load_plugin
unload_plugin
-
+
i_list_formats
i_has_format
-
+
i_color_new
i_color_set
i_color_info
-
+
i_img_empty
i_img_empty_ch
i_img_exorcise
i_img_setmask
i_img_getmask
- i_draw
+ i_line
i_line_aa
i_box
i_box_filled
i_arc
-
+ i_circle_aa
+
i_bezier_multi
i_poly_aa
+ i_poly_aa_cfill
i_copyto
i_rubthru
i_scale_nn
i_haar
i_count_colors
-
-
+
i_gaussian
i_conv
-
+
i_convert
-
+ i_map
+
i_img_diff
i_init_fonts
i_t1_text
i_t1_bbox
-
i_tt_set_aa
i_tt_cp
i_tt_text
i_tt_bbox
- i_readjpeg
- i_writejpeg
-
i_readjpeg_wiol
i_writejpeg_wiol
i_writetiff_wiol
i_writetiff_wiol_faxable
- i_readpng
- i_writepng
+ i_readpng_wiol
+ i_writepng_wiol
i_readgif
+ i_readgif_wiol
i_readgif_callback
i_writegif
i_writegifmc
i_writegif_callback
i_readpnm_wiol
- i_writeppm
+ i_writeppm_wiol
- i_readraw
- i_writeraw
+ i_readraw_wiol
+ i_writeraw_wiol
i_contrast
i_hardinvert
i_postlevels
i_mosaic
i_watermark
-
+
malloc_state
list_formats
-
+
i_gifquant
newfont
newcolour
NC
NF
-
);
-
-
-@EXPORT=qw(
+@EXPORT=qw(
init_log
i_list_formats
i_has_format
unload_plugin
)]);
-
BEGIN {
require Exporter;
require DynaLoader;
- $VERSION = '0.38pre9';
+ $VERSION = '0.41';
@ISA = qw(Exporter DynaLoader);
bootstrap Imager $VERSION;
}
BEGIN {
i_init_fonts(); # Initialize font engines
+ Imager::Font::__init();
for(i_list_formats()) { $formats{$_}++; }
if ($formats{'t1'}) {
i_t1_set_aa(1);
}
- if (!$formats{'t1'} and !$formats{'tt'}) {
+ if (!$formats{'t1'} and !$formats{'tt'}
+ && !$formats{'ft2'} && !$formats{'w32'}) {
$fontstate='no font support';
}
$DEBUG=0;
+ # the members of the subhashes under %filters are:
+ # callseq - a list of the parameters to the underlying filter in the
+ # order they are passed
+ # callsub - a code ref that takes a named parameter list and calls the
+ # underlying filter
+ # defaults - a hash of default values
+ # names - defines names for value of given parameters so if the names
+ # field is foo=> { bar=>1 }, and the user supplies "bar" as the
+ # foo parameter, the filter will receive 1 for the foo
+ # parameter
$filters{contrast}={
callseq => ['image','intensity'],
callsub => sub { my %hsh=@_; i_contrast($hsh{image},$hsh{intensity}); }
defaults => { },
callsub => sub { my %hsh=@_; i_nearest_color($hsh{image}, $hsh{xo}, $hsh{yo}, $hsh{colors}, $hsh{dist}); }
};
+ $filters{gaussian} = {
+ callseq => [ 'image', 'stddev' ],
+ defaults => { },
+ callsub => sub { my %hsh = @_; i_gaussian($hsh{image}, $hsh{stddev}); },
+ };
+ $filters{mosaic} =
+ {
+ callseq => [ qw(image size) ],
+ defaults => { size => 20 },
+ callsub => sub { my %hsh = @_; i_mosaic($hsh{image}, $hsh{size}) },
+ };
+ $filters{bumpmap} =
+ {
+ callseq => [ qw(image bump elevation lightx lighty st) ],
+ defaults => { elevation=>0, st=> 2 },
+ callsub => sub {
+ my %hsh = @_;
+ i_bumpmap($hsh{image}, $hsh{bump}{IMG}, $hsh{elevation},
+ $hsh{lightx}, $hsh{lighty}, $hsh{st});
+ },
+ };
+ $filters{bumpmap_complex} =
+ {
+ callseq => [ qw(image bump channel tx ty Lx Ly Lz cd cs n Ia Il Is) ],
+ defaults => {
+ channel => 0,
+ tx => 0,
+ ty => 0,
+ Lx => 0.2,
+ Ly => 0.4,
+ Lz => -1.0,
+ cd => 1.0,
+ cs => 40,
+ n => 1.3,
+ Ia => Imager::Color->new(rgb=>[0,0,0]),
+ Il => Imager::Color->new(rgb=>[255,255,255]),
+ Is => Imager::Color->new(rgb=>[255,255,255]),
+ },
+ callsub => sub {
+ my %hsh = @_;
+ i_bumpmap_complex($hsh{image}, $hsh{bump}{IMG}, $hsh{channel},
+ $hsh{tx}, $hsh{ty}, $hsh{Lx}, $hsh{Ly}, $hsh{Lz},
+ $hsh{cd}, $hsh{cs}, $hsh{n}, $hsh{Ia}, $hsh{Il},
+ $hsh{Is});
+ },
+ };
+ $filters{postlevels} =
+ {
+ callseq => [ qw(image levels) ],
+ defaults => { levels => 10 },
+ callsub => sub { my %hsh = @_; i_postlevels($hsh{image}, $hsh{levels}); },
+ };
+ $filters{watermark} =
+ {
+ callseq => [ qw(image wmark tx ty pixdiff) ],
+ defaults => { pixdiff=>10, tx=>0, ty=>0 },
+ callsub =>
+ sub {
+ my %hsh = @_;
+ i_watermark($hsh{image}, $hsh{wmark}{IMG}, $hsh{tx}, $hsh{ty},
+ $hsh{pixdiff});
+ },
+ };
+ $filters{fountain} =
+ {
+ callseq => [ qw(image xa ya xb yb ftype repeat combine super_sample ssample_param segments) ],
+ names => {
+ ftype => { linear => 0,
+ bilinear => 1,
+ radial => 2,
+ radial_square => 3,
+ revolution => 4,
+ conical => 5 },
+ repeat => { none => 0,
+ sawtooth => 1,
+ triangle => 2,
+ saw_both => 3,
+ tri_both => 4,
+ },
+ super_sample => {
+ none => 0,
+ grid => 1,
+ random => 2,
+ circle => 3,
+ },
+ combine => {
+ none => 0,
+ normal => 1,
+ multiply => 2, mult => 2,
+ dissolve => 3,
+ add => 4,
+ subtract => 5, 'sub' => 5,
+ diff => 6,
+ lighten => 7,
+ darken => 8,
+ hue => 9,
+ sat => 10,
+ value => 11,
+ color => 12,
+ },
+ },
+ defaults => { ftype => 0, repeat => 0, combine => 0,
+ super_sample => 0, ssample_param => 4,
+ segments=>[
+ [ 0, 0.5, 1,
+ Imager::Color->new(0,0,0),
+ Imager::Color->new(255, 255, 255),
+ 0, 0,
+ ],
+ ],
+ },
+ callsub =>
+ sub {
+ my %hsh = @_;
+ i_fountain($hsh{image}, $hsh{xa}, $hsh{ya}, $hsh{xb}, $hsh{yb},
+ $hsh{ftype}, $hsh{repeat}, $hsh{combine}, $hsh{super_sample},
+ $hsh{ssample_param}, $hsh{segments});
+ },
+ };
+ $filters{unsharpmask} =
+ {
+ callseq => [ qw(image stddev scale) ],
+ defaults => { stddev=>2.0, scale=>1.0 },
+ callsub =>
+ sub {
+ my %hsh = @_;
+ i_unsharp_mask($hsh{image}, $hsh{stddev}, $hsh{scale});
+ },
+ };
$FORMATGUESS=\&def_guess_type;
+
+ $warn_obsolete = 1;
}
#
# print Dumper(@_);
#}
+sub init_log {
+ m_init_log($_[0],$_[1]);
+ log_entry("Imager $VERSION starting\n", 1);
+}
+
+
sub init {
my %parms=(loglevel=>1,@_);
if ($parms{'log'}) {
init_log($parms{'log'},$parms{'loglevel'});
}
+ if (exists $parms{'warn_obsolete'}) {
+ $warn_obsolete = $parms{'warn_obsolete'};
+ }
+
# if ($parms{T1LIB_CONFIG}) { $ENV{T1LIB_CONFIG}=$parms{T1LIB_CONFIG}; }
# if ( $ENV{T1LIB_CONFIG} and ( $fontstate eq 'missing conf' )) {
# i_init_fonts();
# $fontstate='ok';
# }
+ if (exists $parms{'t1log'}) {
+ i_init_fonts($parms{'t1log'});
+ }
}
END {
return join(": ", map $_->[0], i_errors());
}
+# this function tries to DWIM for color parameters
+# color objects are used as is
+# simple scalars are simply treated as single parameters to Imager::Color->new
+# hashrefs are treated as named argument lists to Imager::Color->new
+# arrayrefs are treated as list arguments to Imager::Color->new iff any
+# parameter is > 1
+# other arrayrefs are treated as list arguments to Imager::Color::Float
+
+sub _color {
+ my $arg = shift;
+ # perl 5.6.0 seems to do weird things to $arg if we don't make an
+ # explicitly stringified copy
+ # I vaguely remember a bug on this on p5p, but couldn't find it
+ # through bugs.perl.org (I had trouble getting it to find any bugs)
+ my $copy = $arg . "";
+ my $result;
+
+ if (ref $arg) {
+ if (UNIVERSAL::isa($arg, "Imager::Color")
+ || UNIVERSAL::isa($arg, "Imager::Color::Float")) {
+ $result = $arg;
+ }
+ else {
+ if ($copy =~ /^HASH\(/) {
+ $result = Imager::Color->new(%$arg);
+ }
+ elsif ($copy =~ /^ARRAY\(/) {
+ if (grep $_ > 1, @$arg) {
+ $result = Imager::Color->new(@$arg);
+ }
+ else {
+ $result = Imager::Color::Float->new(@$arg);
+ }
+ }
+ else {
+ $Imager::ERRSTR = "Not a color";
+ }
+ }
+ }
+ else {
+ # assume Imager::Color::new knows how to handle it
+ $result = Imager::Color->new($arg);
+ }
+
+ return $result;
+}
+
#
# Methods to be called on objects.
return $self;
}
-
# Copy an entire image with no changes
# - if an image has magic the copy of it will not be magical
sub img_set {
my $self=shift;
- my %hsh=(xsize=>100,ysize=>100,channels=>3,@_);
+ my %hsh=(xsize=>100, ysize=>100, channels=>3, bits=>8, type=>'direct', @_);
if (defined($self->{IMG})) {
- i_img_destroy($self->{IMG});
+ # let IIM_DESTROY destroy it, it's possible this image is
+ # referenced from a virtual image (like masked)
+ #i_img_destroy($self->{IMG});
undef($self->{IMG});
}
- $self->{IMG}=Imager::ImgRaw::new($hsh{'xsize'},$hsh{'ysize'},$hsh{'channels'});
+ if ($hsh{type} eq 'paletted' || $hsh{type} eq 'pseudo') {
+ $self->{IMG} = i_img_pal_new($hsh{xsize}, $hsh{ysize}, $hsh{channels},
+ $hsh{maxcolors} || 256);
+ }
+ elsif ($hsh{bits} eq 'double') {
+ $self->{IMG} = i_img_double_new($hsh{xsize}, $hsh{ysize}, $hsh{channels});
+ }
+ elsif ($hsh{bits} == 16) {
+ $self->{IMG} = i_img_16_new($hsh{xsize}, $hsh{ysize}, $hsh{channels});
+ }
+ else {
+ $self->{IMG}=Imager::ImgRaw::new($hsh{'xsize'}, $hsh{'ysize'},
+ $hsh{'channels'});
+ }
}
-# Read an image from file
-
-sub read {
+# created a masked version of the current image
+sub masked {
my $self = shift;
- my %input=@_;
- my ($fh, $fd, $IO);
- if (defined($self->{IMG})) {
- i_img_destroy($self->{IMG});
- undef($self->{IMG});
- }
+ $self or return undef;
+ my %opts = (left => 0,
+ top => 0,
+ right => $self->getwidth,
+ bottom => $self->getheight,
+ @_);
+ my $mask = $opts{mask} ? $opts{mask}{IMG} : undef;
+
+ my $result = Imager->new;
+ $result->{IMG} = i_img_masked_new($self->{IMG}, $mask, $opts{left},
+ $opts{top}, $opts{right} - $opts{left},
+ $opts{bottom} - $opts{top});
+ # keep references to the mask and base images so they don't
+ # disappear on us
+ $result->{DEPENDS} = [ $self->{IMG}, $mask ];
+
+ $result;
+}
- if (!$input{fd} and !$input{file} and !$input{data}) { $self->{ERRSTR}='no file, fd or data parameter'; return undef; }
- if ($input{file}) {
- $fh = new IO::File($input{file},"r");
- if (!defined $fh) { $self->{ERRSTR}='Could not open file'; return undef; }
- binmode($fh);
- $fd = $fh->fileno();
+# convert an RGB image into a paletted image
+sub to_paletted {
+ my $self = shift;
+ my $opts;
+ if (@_ != 1 && !ref $_[0]) {
+ $opts = { @_ };
+ }
+ else {
+ $opts = shift;
}
- if ($input{fd}) { $fd=$input{fd} };
- # FIXME: Find the format here if not specified
- # yes the code isn't here yet - next week maybe?
+ my $result = Imager->new;
+ $result->{IMG} = i_img_to_pal($self->{IMG}, $opts);
- if (!$input{type} and $input{file}) { $input{type}=$FORMATGUESS->($input{file}); }
- if (!$formats{$input{type}}) { $self->{ERRSTR}='format not supported'; return undef; }
+ #print "Type ", i_img_type($result->{IMG}), "\n";
- my %iolready=(jpeg=>1, tiff=>1, pnm=>1);
+ $result->{IMG} or undef $result;
- if ($iolready{$input{type}}) {
- # Setup data source
- $IO = io_new_fd($fd); # sort of simple for now eh?
+ return $result;
+}
- if ( $input{type} eq 'jpeg' ) {
- ($self->{IMG},$self->{IPTCRAW})=i_readjpeg_wiol( $IO );
- if ( !defined($self->{IMG}) ) { $self->{ERRSTR}='unable to read jpeg image'; return undef; }
- $self->{DEBUG} && print "loading a jpeg file\n";
- return $self;
- }
+# convert a paletted (or any image) to an 8-bit/channel RGB images
+sub to_rgb8 {
+ my $self = shift;
+ my $result;
- if ( $input{type} eq 'tiff' ) {
- $self->{IMG}=i_readtiff_wiol( $IO, -1 ); # Fixme, check if that length parameter is ever needed
- if ( !defined($self->{IMG}) ) { $self->{ERRSTR}='unable to read tiff image'; return undef; }
- $self->{DEBUG} && print "loading a tiff file\n";
- return $self;
- }
+ if ($self->{IMG}) {
+ $result = Imager->new;
+ $result->{IMG} = i_img_to_rgb($self->{IMG})
+ or undef $result;
+ }
- if ( $input{type} eq 'pnm' ) {
- $self->{IMG}=i_readpnm_wiol( $IO, -1 ); # Fixme, check if that length parameter is ever needed
- if ( !defined($self->{IMG}) ) { $self->{ERRSTR}='unable to read pnm image: '._error_as_msg(); return undef; }
- $self->{DEBUG} && print "loading a pnm file\n";
- return $self;
- }
+ return $result;
+}
- } else {
+sub addcolors {
+ my $self = shift;
+ my %opts = (colors=>[], @_);
- # Old code for reference while changing the new stuff
+ @{$opts{colors}} or return undef;
+ $self->{IMG} and i_addcolors($self->{IMG}, @{$opts{colors}});
+}
- if (!$input{type} and $input{file}) { $input{type}=$FORMATGUESS->($input{file}); }
- if (!$input{type}) { $self->{ERRSTR}='type parameter missing and not possible to guess from extension'; return undef; }
+sub setcolors {
+ my $self = shift;
+ my %opts = (start=>0, colors=>[], @_);
+ @{$opts{colors}} or return undef;
- if (!$formats{$input{type}}) { $self->{ERRSTR}='format not supported'; return undef; }
+ $self->{IMG} and i_setcolors($self->{IMG}, $opts{start}, @{$opts{colors}});
+}
- if ($input{file}) {
- $fh = new IO::File($input{file},"r");
- if (!defined $fh) { $self->{ERRSTR}='Could not open file'; return undef; }
- binmode($fh);
- $fd = $fh->fileno();
+sub getcolors {
+ my $self = shift;
+ my %opts = @_;
+ if (!exists $opts{start} && !exists $opts{count}) {
+ # get them all
+ $opts{start} = 0;
+ $opts{count} = $self->colorcount;
}
- if ($input{fd}) { $fd=$input{fd} };
-
- if ( $input{type} eq 'gif' ) {
- my $colors;
- if ($input{colors} && !ref($input{colors})) {
- # must be a reference to a scalar that accepts the colour map
- $self->{ERRSTR} = "option 'colors' must be a scalar reference";
- return undef;
- }
- if (exists $input{data}) {
- if ($input{colors}) {
- ($self->{IMG}, $colors) = i_readgif_scalar($input{data});
- }
- else {
- $self->{IMG}=i_readgif_scalar($input{data});
- }
- }
- else {
- if ($input{colors}) {
- ($self->{IMG}, $colors) = i_readgif( $fd );
- }
- else {
- $self->{IMG} = i_readgif( $fd )
- }
- }
- if ($colors) {
- # we may or may not change i_readgif to return blessed objects...
- ${$input{colors}} = [ map { NC(@$_) } @$colors ];
- }
- if ( !defined($self->{IMG}) ) {
- $self->{ERRSTR}= 'reading GIF:'._error_as_msg(); return undef;
- }
- $self->{DEBUG} && print "loading a gif file\n";
- } elsif ( $input{type} eq 'jpeg' ) {
- if (exists $input{data}) { ($self->{IMG},$self->{IPTCRAW})=i_readjpeg_scalar($input{data}); }
- else { ($self->{IMG},$self->{IPTCRAW})=i_readjpeg( $fd ); }
- if ( !defined($self->{IMG}) ) { $self->{ERRSTR}='unable to read jpeg image'; return undef; }
- $self->{DEBUG} && print "loading a jpeg file\n";
- } elsif ( $input{type} eq 'png' ) {
- if (exists $input{data}) { $self->{IMG}=i_readpng_scalar($input{data}); }
- else { $self->{IMG}=i_readpng( $fd ); }
- if ( !defined($self->{IMG}) ) { $self->{ERRSTR}='unable to read png image'; return undef; }
- $self->{DEBUG} && print "loading a png file\n";
- } elsif ( $input{type} eq 'raw' ) {
- my %params=(datachannels=>3,storechannels=>3,interleave=>1);
- for(keys(%input)) { $params{$_}=$input{$_}; }
-
- if ( !($params{xsize} && $params{ysize}) ) { $self->{ERRSTR}='missing xsize or ysize parameter for raw'; return undef; }
- $self->{IMG}=i_readraw( $fd, $params{xsize}, $params{ysize},
- $params{datachannels}, $params{storechannels}, $params{interleave});
- if ( !defined($self->{IMG}) ) { $self->{ERRSTR}='unable to read raw image'; return undef; }
- $self->{DEBUG} && print "loading a raw file\n";
+ elsif (!exists $opts{count}) {
+ $opts{count} = 1;
}
- return $self;
+ elsif (!exists $opts{start}) {
+ $opts{start} = 0;
}
+
+ $self->{IMG} and
+ return i_getcolors($self->{IMG}, $opts{start}, $opts{count});
}
+sub colorcount {
+ i_colorcount($_[0]{IMG});
+}
-# Write an image to file
+sub maxcolors {
+ i_maxcolors($_[0]{IMG});
+}
-sub write {
+sub findcolor {
my $self = shift;
- my %input=(jpegquality=>75, gifquant=>'mc', lmdither=>6.0, lmfixed=>[],
- fax_fine=>1, @_);
- my ($fh, $rc, $fd, $IO);
-
- my %iolready=( tiff=>1 ); # this will be SO MUCH BETTER once they are all in there
-
- unless ($self->{IMG}) { $self->{ERRSTR}='empty input image'; return undef; }
+ my %opts = @_;
+ $opts{color} or return undef;
- if (!$input{file} and !$input{'fd'} and !$input{'data'}) { $self->{ERRSTR}='file/fd/data parameter missing'; return undef; }
- if (!$input{type} and $input{file}) { $input{type}=$FORMATGUESS->($input{file}); }
- if (!$input{type}) { $self->{ERRSTR}='type parameter missing and not possible to guess from extension'; return undef; }
+ $self->{IMG} and i_findcolor($self->{IMG}, $opts{color});
+}
- if (!$formats{$input{type}}) { $self->{ERRSTR}='format not supported'; return undef; }
+sub bits {
+ my $self = shift;
+ my $bits = $self->{IMG} && i_img_bits($self->{IMG});
+ if ($bits && $bits == length(pack("d", 1)) * 8) {
+ $bits = 'double';
+ }
+ $bits;
+}
- if (exists $input{'fd'}) {
- $fd=$input{'fd'};
- } elsif (exists $input{'data'}) {
- $IO = Imager::io_new_bufchain();
- } else {
- $fh = new IO::File($input{file},"w+");
- if (!defined $fh) { $self->{ERRSTR}='Could not open file'; return undef; }
- binmode($fh);
- $fd = $fh->fileno();
+sub type {
+ my $self = shift;
+ if ($self->{IMG}) {
+ return i_img_type($self->{IMG}) ? "paletted" : "direct";
}
+}
+sub virtual {
+ my $self = shift;
+ $self->{IMG} and i_img_virtual($self->{IMG});
+}
+
+sub tags {
+ my ($self, %opts) = @_;
+ $self->{IMG} or return;
- if ($iolready{$input{type}}) {
- if (defined $fd) {
- $IO = io_new_fd($fd);
+ if (defined $opts{name}) {
+ my @result;
+ my $start = 0;
+ my $found;
+ while (defined($found = i_tags_find($self->{IMG}, $opts{name}, $start))) {
+ push @result, (i_tags_get($self->{IMG}, $found))[1];
+ $start = $found+1;
}
+ return wantarray ? @result : $result[0];
+ }
+ elsif (defined $opts{code}) {
+ my @result;
+ my $start = 0;
+ my $found;
+ while (defined($found = i_tags_findn($self->{IMG}, $opts{code}, $start))) {
+ push @result, (i_tags_get($self->{IMG}, $found))[1];
+ $start = $found+1;
+ }
+ return @result;
+ }
+ else {
+ if (wantarray) {
+ return map { [ i_tags_get($self->{IMG}, $_) ] } 0.. i_tags_count($self->{IMG})-1;
+ }
+ else {
+ return i_tags_count($self->{IMG});
+ }
+ }
+}
- if ($input{type} eq 'tiff') {
- if (defined $input{class} && $input{class} eq 'fax') {
- if (!i_writetiff_wiol_faxable($self->{IMG}, $IO, $input{fax_fine})) {
- $self->{ERRSTR}='Could not write to buffer';
- return undef;
- }
+sub addtag {
+ my $self = shift;
+ my %opts = @_;
+
+ return -1 unless $self->{IMG};
+ if ($opts{name}) {
+ if (defined $opts{value}) {
+ if ($opts{value} =~ /^\d+$/) {
+ # add as a number
+ return i_tags_addn($self->{IMG}, $opts{name}, 0, $opts{value});
}
else {
- if (!i_writetiff_wiol($self->{IMG}, $IO)) {
- $self->{ERRSTR}='Could not write to buffer';
- return undef;
- }
+ return i_tags_add($self->{IMG}, $opts{name}, 0, $opts{value}, 0);
}
}
-
- if (exists $input{'data'}) {
- my $data = io_slurp($IO);
- if (!$data) {
- $self->{ERRSTR}='Could not slurp from buffer';
- return undef;
- }
- ${$input{data}} = $data;
+ elsif (defined $opts{data}) {
+ # force addition as a string
+ return i_tags_add($self->{IMG}, $opts{name}, 0, $opts{data}, 0);
}
- return $self;
- } else {
-
- if ( $input{type} eq 'gif' ) {
- if (not $input{gifplanes}) {
- my $gp;
- my $count=i_count_colors($self->{IMG}, 256);
- $gp=8 if $count == -1;
- $gp=1 if not $gp and $count <= 2;
- $gp=2 if not $gp and $count <= 4;
- $gp=3 if not $gp and $count <= 8;
- $gp=4 if not $gp and $count <= 16;
- $gp=5 if not $gp and $count <= 32;
- $gp=6 if not $gp and $count <= 64;
- $gp=7 if not $gp and $count <= 128;
- $input{gifplanes} = $gp || 8;
+ else {
+ $self->{ERRSTR} = "No value supplied";
+ return undef;
+ }
+ }
+ elsif ($opts{code}) {
+ if (defined $opts{value}) {
+ if ($opts{value} =~ /^\d+$/) {
+ # add as a number
+ return i_tags_addn($self->{IMG}, $opts{code}, 0, $opts{value});
}
-
- if ($input{gifplanes}>8) {
- $input{gifplanes}=8;
+ else {
+ return i_tags_add($self->{IMG}, $opts{code}, 0, $opts{value}, 0);
}
- if ($input{gifquant} eq 'gen' || $input{callback}) {
+ }
+ elsif (defined $opts{data}) {
+ # force addition as a string
+ return i_tags_add($self->{IMG}, $opts{code}, 0, $opts{data}, 0);
+ }
+ else {
+ $self->{ERRSTR} = "No value supplied";
+ return undef;
+ }
+ }
+ else {
+ return undef;
+ }
+}
+sub deltag {
+ my $self = shift;
+ my %opts = @_;
- if ($input{gifquant} eq 'lm') {
+ return 0 unless $self->{IMG};
- $input{make_colors} = 'addi';
- $input{translate} = 'perturb';
- $input{perturb} = $input{lmdither};
- } elsif ($input{gifquant} eq 'gen') {
- # just pass options through
- } else {
- $input{make_colors} = 'webmap'; # ignored
- $input{translate} = 'giflib';
- }
+ if (defined $opts{'index'}) {
+ return i_tags_delete($self->{IMG}, $opts{'index'});
+ }
+ elsif (defined $opts{name}) {
+ return i_tags_delbyname($self->{IMG}, $opts{name});
+ }
+ elsif (defined $opts{code}) {
+ return i_tags_delbycode($self->{IMG}, $opts{code});
+ }
+ else {
+ $self->{ERRSTR} = "Need to supply index, name, or code parameter";
+ return 0;
+ }
+}
- if ($input{callback}) {
- defined $input{maxbuffer} or $input{maxbuffer} = -1;
- $rc = i_writegif_callback($input{callback}, $input{maxbuffer},
- \%input, $self->{IMG});
- } else {
- $rc = i_writegif_gen($fd, \%input, $self->{IMG});
- }
+sub settag {
+ my ($self, %opts) = @_;
+ if ($opts{name}) {
+ $self->deltag(name=>$opts{name});
+ return $self->addtag(name=>$opts{name}, value=>$opts{value});
+ }
+ elsif (defined $opts{code}) {
+ $self->deltag(code=>$opts{code});
+ return $self->addtag(code=>$opts{code}, value=>$opts{value});
+ }
+ else {
+ return undef;
+ }
+}
+my @needseekcb = qw/tiff/;
+my %needseekcb = map { $_, $_ } @needseekcb;
- } elsif ($input{gifquant} eq 'lm') {
- $rc=i_writegif($self->{IMG},$fd,$input{gifplanes},$input{lmdither},$input{lmfixed});
- } else {
- $rc=i_writegifmc($self->{IMG},$fd,$input{gifplanes});
- }
- if ( !defined($rc) ) {
- $self->{ERRSTR} = "Writing GIF file: "._error_as_msg(); return undef;
- }
- $self->{DEBUG} && print "writing a gif file\n";
- } elsif ( $input{type} eq 'jpeg' ) {
- $rc=i_writejpeg($self->{IMG},$fd,$input{jpegquality});
- if ( !defined($rc) ) {
- $self->{ERRSTR}='unable to write jpeg image'; return undef;
- }
- $self->{DEBUG} && print "writing a jpeg file\n";
- } elsif ( $input{type} eq 'png' ) {
- $rc=i_writepng($self->{IMG},$fd);
- if ( !defined($rc) ) {
- $self->{ERRSTR}='unable to write png image'; return undef;
- }
- $self->{DEBUG} && print "writing a png file\n";
- } elsif ( $input{type} eq 'pnm' ) {
- $rc=i_writeppm($self->{IMG},$fd);
- if ( !defined($rc) ) {
- $self->{ERRSTR}='unable to write pnm image'; return undef;
- }
- $self->{DEBUG} && print "writing a pnm file\n";
- } elsif ( $input{type} eq 'raw' ) {
- $rc=i_writeraw($self->{IMG},$fd);
- if ( !defined($rc) ) {
- $self->{ERRSTR}='unable to write raw image'; return undef;
- }
- $self->{DEBUG} && print "writing a raw file\n";
- }
+sub _get_reader_io {
+ my ($self, $input, $type) = @_;
+ if ($input->{fd}) {
+ return io_new_fd($input->{fd});
}
- return $self;
-}
-
-sub write_multi {
- my ($class, $opts, @images) = @_;
-
- if ($opts->{type} eq 'gif') {
- my $gif_delays = $opts->{gif_delays};
- local $opts->{gif_delays} = $gif_delays;
- unless (ref $opts->{gif_delays}) {
- # assume the caller wants the same delay for each frame
- $opts->{gif_delays} = [ ($gif_delays) x @images ];
+ elsif ($input->{fh}) {
+ my $fd = fileno($input->{fh});
+ unless ($fd) {
+ $self->_set_error("Handle in fh option not opened");
+ return;
}
- # translate to ImgRaw
- if (grep !UNIVERSAL::isa($_, 'Imager') || !$_->{IMG}, @images) {
- $ERRSTR = "Usage: Imager->write_multi({ options }, @images)";
- return 0;
+ return io_new_fd($fd);
+ }
+ elsif ($input->{file}) {
+ my $file = IO::File->new($input->{file}, "r");
+ unless ($file) {
+ $self->_set_error("Could not open $input->{file}: $!");
+ return;
}
- my @work = map $_->{IMG}, @images;
- if ($opts->{callback}) {
- # Note: you may need to fix giflib for this one to work
- my $maxbuffer = $opts->{maxbuffer};
- defined $maxbuffer or $maxbuffer = -1; # max by default
- return i_writegif_callback($opts->{callback}, $maxbuffer,
- $opts, @work);
+ binmode $file;
+ return (io_new_fd(fileno($file)), $file);
+ }
+ elsif ($input->{data}) {
+ return io_new_buffer($input->{data});
+ }
+ elsif ($input->{callback} || $input->{readcb}) {
+ if ($needseekcb{$type} && !$input->{seekcb}) {
+ $self->_set_error("Format $type needs a seekcb parameter");
}
- if ($opts->{fd}) {
- return i_writegif_gen($opts->{fd}, $opts, @work);
+ if ($input->{maxbuffer}) {
+ return io_new_cb($input->{writecb},
+ $input->{callback} || $input->{readcb},
+ $input->{seekcb}, $input->{closecb},
+ $input->{maxbuffer});
}
else {
- my $fh = IO::File->new($opts->{file}, "w+");
- unless ($fh) {
- $ERRSTR = "Error creating $opts->{file}: $!";
- return 0;
- }
- binmode($fh);
- return i_writegif_gen(fileno($fh), $opts, @work);
+ return io_new_cb($input->{writecb},
+ $input->{callback} || $input->{readcb},
+ $input->{seekcb}, $input->{closecb});
}
}
else {
- $ERRSTR = "Sorry, write_multi doesn't support $opts->{type} yet";
- return 0;
+ $self->_set_error("file/fd/fh/data/callback parameter missing");
+ return;
}
}
-# Destroy an Imager object
+sub _get_writer_io {
+ my ($self, $input, $type) = @_;
-sub DESTROY {
- my $self=shift;
- # delete $instances{$self};
- if (defined($self->{IMG})) {
- i_img_destroy($self->{IMG});
- undef($self->{IMG});
- } else {
-# print "Destroy Called on an empty image!\n"; # why did I put this here??
+ if ($input->{fd}) {
+ return io_new_fd($input->{fd});
+ }
+ elsif ($input->{fh}) {
+ my $fd = fileno($input->{fh});
+ unless ($fd) {
+ $self->_set_error("Handle in fh option not opened");
+ return;
+ }
+ # flush it
+ my $oldfh = select($input->{fh});
+ # flush anything that's buffered, and make sure anything else is flushed
+ $| = 1;
+ select($oldfh);
+ return io_new_fd($fd);
+ }
+ elsif ($input->{file}) {
+ my $fh = new IO::File($input->{file},"w+");
+ unless ($fh) {
+ $self->_set_error("Could not open file $input->{file}: $!");
+ return;
+ }
+ binmode($fh) or die;
+ return (io_new_fd(fileno($fh)), $fh);
+ }
+ elsif ($input->{data}) {
+ return io_new_bufchain();
+ }
+ elsif ($input->{callback} || $input->{writecb}) {
+ if ($input->{maxbuffer}) {
+ return io_new_cb($input->{callback} || $input->{writecb},
+ $input->{readcb},
+ $input->{seekcb}, $input->{closecb},
+ $input->{maxbuffer});
+ }
+ else {
+ return io_new_cb($input->{callback} || $input->{writecb},
+ $input->{readcb},
+ $input->{seekcb}, $input->{closecb});
+ }
+ }
+ else {
+ $self->_set_error("file/fd/fh/data/callback parameter missing");
+ return;
}
}
-# Perform an inplace filter of an image
-# that is the image will be overwritten with the data
+# Read an image from file
-sub filter {
- my $self=shift;
+sub read {
+ my $self = shift;
my %input=@_;
- my %hsh;
- unless ($self->{IMG}) { $self->{ERRSTR}='empty input image'; return undef; }
- if (!$input{type}) { $self->{ERRSTR}='type parameter missing'; return undef; }
-
- if ( (grep { $_ eq $input{type} } keys %filters) != 1) {
- $self->{ERRSTR}='type parameter not matching any filter'; return undef;
+ if (defined($self->{IMG})) {
+ # let IIM_DESTROY do the destruction, since the image may be
+ # referenced from elsewhere
+ #i_img_destroy($self->{IMG});
+ undef($self->{IMG});
}
- if (defined($filters{$input{type}}{defaults})) {
- %hsh=('image',$self->{IMG},%{$filters{$input{type}}{defaults}},%input);
- } else {
- %hsh=('image',$self->{IMG},%input);
+ # FIXME: Find the format here if not specified
+ # yes the code isn't here yet - next week maybe?
+ # Next week? Are you high or something? That comment
+ # has been there for half a year dude.
+ # Look, i just work here, ok?
+
+ if (!$input{'type'} and $input{file}) {
+ $input{'type'}=$FORMATGUESS->($input{file});
+ }
+ unless ($input{'type'}) {
+ $self->_set_error('type parameter missing and not possible to guess from extension');
+ return undef;
+ }
+ if (!$formats{$input{'type'}}) {
+ $self->{ERRSTR}='format not supported'; return undef;
}
- my @cs=@{$filters{$input{type}}{callseq}};
+ my %iolready=(jpeg=>1, png=>1, tiff=>1, pnm=>1, raw=>1, bmp=>1, tga=>1, rgb=>1, gif=>1);
- for(@cs) {
- if (!defined($hsh{$_})) {
- $self->{ERRSTR}="missing parameter '$_' for filter ".$input{type}; return undef;
+ if ($iolready{$input{'type'}}) {
+ # Setup data source
+ my ($IO, $fh) = $self->_get_reader_io(\%input, $input{'type'})
+ or return;
+
+ if ( $input{'type'} eq 'jpeg' ) {
+ ($self->{IMG},$self->{IPTCRAW})=i_readjpeg_wiol( $IO );
+ if ( !defined($self->{IMG}) ) {
+ $self->{ERRSTR}='unable to read jpeg image'; return undef;
+ }
+ $self->{DEBUG} && print "loading a jpeg file\n";
+ return $self;
+ }
+
+ if ( $input{'type'} eq 'tiff' ) {
+ $self->{IMG}=i_readtiff_wiol( $IO, -1 ); # Fixme, check if that length parameter is ever needed
+ if ( !defined($self->{IMG}) ) {
+ $self->{ERRSTR}=$self->_error_as_msg(); return undef;
+ }
+ $self->{DEBUG} && print "loading a tiff file\n";
+ return $self;
+ }
+
+ if ( $input{'type'} eq 'pnm' ) {
+ $self->{IMG}=i_readpnm_wiol( $IO, -1 ); # Fixme, check if that length parameter is ever needed
+ if ( !defined($self->{IMG}) ) {
+ $self->{ERRSTR}='unable to read pnm image: '._error_as_msg(); return undef;
+ }
+ $self->{DEBUG} && print "loading a pnm file\n";
+ return $self;
+ }
+
+ if ( $input{'type'} eq 'png' ) {
+ $self->{IMG}=i_readpng_wiol( $IO, -1 ); # Fixme, check if that length parameter is ever needed
+ if ( !defined($self->{IMG}) ) {
+ $self->{ERRSTR}='unable to read png image';
+ return undef;
+ }
+ $self->{DEBUG} && print "loading a png file\n";
+ }
+
+ if ( $input{'type'} eq 'bmp' ) {
+ $self->{IMG}=i_readbmp_wiol( $IO );
+ if ( !defined($self->{IMG}) ) {
+ $self->{ERRSTR}=$self->_error_as_msg();
+ return undef;
+ }
+ $self->{DEBUG} && print "loading a bmp file\n";
+ }
+
+ if ( $input{'type'} eq 'gif' ) {
+ if ($input{colors} && !ref($input{colors})) {
+ # must be a reference to a scalar that accepts the colour map
+ $self->{ERRSTR} = "option 'colors' must be a scalar reference";
+ return undef;
+ }
+ if ($input{colors}) {
+ my $colors;
+ ($self->{IMG}, $colors) =i_readgif_wiol( $IO );
+ if ($colors) {
+ ${ $input{colors} } = [ map { NC(@$_) } @$colors ];
+ }
+ }
+ else {
+ $self->{IMG} =i_readgif_wiol( $IO );
+ }
+ if ( !defined($self->{IMG}) ) {
+ $self->{ERRSTR}=$self->_error_as_msg();
+ return undef;
+ }
+ $self->{DEBUG} && print "loading a gif file\n";
+ }
+
+ if ( $input{'type'} eq 'tga' ) {
+ $self->{IMG}=i_readtga_wiol( $IO, -1 ); # Fixme, check if that length parameter is ever needed
+ if ( !defined($self->{IMG}) ) {
+ $self->{ERRSTR}=$self->_error_as_msg();
+ return undef;
+ }
+ $self->{DEBUG} && print "loading a tga file\n";
+ }
+
+ if ( $input{'type'} eq 'rgb' ) {
+ $self->{IMG}=i_readrgb_wiol( $IO, -1 ); # Fixme, check if that length parameter is ever needed
+ if ( !defined($self->{IMG}) ) {
+ $self->{ERRSTR}=$self->_error_as_msg();
+ return undef;
+ }
+ $self->{DEBUG} && print "loading a tga file\n";
+ }
+
+
+ if ( $input{'type'} eq 'raw' ) {
+ my %params=(datachannels=>3,storechannels=>3,interleave=>1,%input);
+
+ if ( !($params{xsize} && $params{ysize}) ) {
+ $self->{ERRSTR}='missing xsize or ysize parameter for raw';
+ return undef;
+ }
+
+ $self->{IMG} = i_readraw_wiol( $IO,
+ $params{xsize},
+ $params{ysize},
+ $params{datachannels},
+ $params{storechannels},
+ $params{interleave});
+ if ( !defined($self->{IMG}) ) {
+ $self->{ERRSTR}='unable to read raw image';
+ return undef;
+ }
+ $self->{DEBUG} && print "loading a raw file\n";
+ }
+
+ } else {
+
+ # Old code for reference while changing the new stuff
+
+ if (!$input{'type'} and $input{file}) {
+ $input{'type'}=$FORMATGUESS->($input{file});
+ }
+
+ if (!$input{'type'}) {
+ $self->{ERRSTR}='type parameter missing and not possible to guess from extension'; return undef;
+ }
+
+ if (!$formats{$input{'type'}}) {
+ $self->{ERRSTR}='format not supported';
+ return undef;
+ }
+
+ my ($fh, $fd);
+ if ($input{file}) {
+ $fh = new IO::File($input{file},"r");
+ if (!defined $fh) {
+ $self->{ERRSTR}='Could not open file';
+ return undef;
+ }
+ binmode($fh);
+ $fd = $fh->fileno();
+ }
+
+ if ($input{fd}) {
+ $fd=$input{fd};
+ }
+
+ if ( $input{'type'} eq 'gif' ) {
+ my $colors;
+ if ($input{colors} && !ref($input{colors})) {
+ # must be a reference to a scalar that accepts the colour map
+ $self->{ERRSTR} = "option 'colors' must be a scalar reference";
+ return undef;
+ }
+ if (exists $input{data}) {
+ if ($input{colors}) {
+ ($self->{IMG}, $colors) = i_readgif_scalar($input{data});
+ } else {
+ $self->{IMG}=i_readgif_scalar($input{data});
+ }
+ } else {
+ if ($input{colors}) {
+ ($self->{IMG}, $colors) = i_readgif( $fd );
+ } else {
+ $self->{IMG} = i_readgif( $fd )
+ }
+ }
+ if ($colors) {
+ # we may or may not change i_readgif to return blessed objects...
+ ${ $input{colors} } = [ map { NC(@$_) } @$colors ];
+ }
+ if ( !defined($self->{IMG}) ) {
+ $self->{ERRSTR}= 'reading GIF:'._error_as_msg();
+ return undef;
+ }
+ $self->{DEBUG} && print "loading a gif file\n";
+ }
+ }
+ return $self;
+}
+
+sub _fix_gif_positions {
+ my ($opts, $opt, $msg, @imgs) = @_;
+
+ my $positions = $opts->{'gif_positions'};
+ my $index = 0;
+ for my $pos (@$positions) {
+ my ($x, $y) = @$pos;
+ my $img = $imgs[$index++];
+ $img->settag(name=>'gif_left', value=>$x);
+ $img->settag(name=>'gif_top', value=>$y) if defined $y;
+ }
+ $$msg .= "replaced with the gif_left and gif_top tags";
+}
+
+my %obsolete_opts =
+ (
+ gif_each_palette=>'gif_local_map',
+ interlace => 'gif_interlace',
+ gif_delays => 'gif_delay',
+ gif_positions => \&_fix_gif_positions,
+ gif_loop_count => 'gif_loop',
+ );
+
+sub _set_opts {
+ my ($self, $opts, $prefix, @imgs) = @_;
+
+ for my $opt (keys %$opts) {
+ my $tagname = $opt;
+ if ($obsolete_opts{$opt}) {
+ my $new = $obsolete_opts{$opt};
+ my $msg = "Obsolete option $opt ";
+ if (ref $new) {
+ $new->($opts, $opt, \$msg, @imgs);
+ }
+ else {
+ $msg .= "replaced with the $new tag ";
+ $tagname = $new;
+ }
+ $msg .= "line ".(caller(2))[2]." of file ".(caller(2))[1];
+ warn $msg if $warn_obsolete && $^W;
+ }
+ next unless $tagname =~ /^\Q$prefix/;
+ my $value = $opts->{$opt};
+ if (ref $value) {
+ if (UNIVERSAL::isa($value, "Imager::Color")) {
+ my $tag = sprintf("color(%d,%d,%d,%d)", $value->rgba);
+ for my $img (@imgs) {
+ $img->settag(name=>$tagname, value=>$tag);
+ }
+ }
+ elsif (ref($value) eq 'ARRAY') {
+ for my $i (0..$#$value) {
+ my $val = $value->[$i];
+ if (ref $val) {
+ if (UNIVERSAL::isa($val, "Imager::Color")) {
+ my $tag = sprintf("color(%d,%d,%d,%d)", $value->rgba);
+ $i < @imgs and
+ $imgs[$i]->settag(name=>$tagname, value=>$tag);
+ }
+ else {
+ $self->_set_error("Unknown reference type " . ref($value) .
+ " supplied in array for $opt");
+ return;
+ }
+ }
+ else {
+ $i < @imgs
+ and $imgs[$i]->settag(name=>$tagname, value=>$val);
+ }
+ }
+ }
+ else {
+ $self->_set_error("Unknown reference type " . ref($value) .
+ " supplied for $opt");
+ return;
+ }
+ }
+ else {
+ # set it as a tag for every image
+ for my $img (@imgs) {
+ $img->settag(name=>$tagname, value=>$value);
+ }
+ }
+ }
+
+ return 1;
+}
+
+# Write an image to file
+sub write {
+ my $self = shift;
+ my %input=(jpegquality=>75,
+ gifquant=>'mc',
+ lmdither=>6.0,
+ lmfixed=>[],
+ idstring=>"",
+ compress=>1,
+ wierdpack=>0,
+ fax_fine=>1, @_);
+ my $rc;
+
+ $self->_set_opts(\%input, "i_", $self)
+ or return undef;
+
+ my %iolready=( tiff=>1, raw=>1, png=>1, pnm=>1, bmp=>1, jpeg=>1, tga=>1,
+ gif=>1 ); # this will be SO MUCH BETTER once they are all in there
+
+ unless ($self->{IMG}) { $self->{ERRSTR}='empty input image'; return undef; }
+
+ if (!$input{'type'} and $input{file}) {
+ $input{'type'}=$FORMATGUESS->($input{file});
+ }
+ if (!$input{'type'}) {
+ $self->{ERRSTR}='type parameter missing and not possible to guess from extension';
+ return undef;
+ }
+
+ if (!$formats{$input{'type'}}) { $self->{ERRSTR}='format not supported'; return undef; }
+
+ my ($IO, $fh) = $self->_get_writer_io(\%input, $input{'type'})
+ or return undef;
+
+ # this conditional is probably obsolete
+ if ($iolready{$input{'type'}}) {
+
+ if ($input{'type'} eq 'tiff') {
+ $self->_set_opts(\%input, "tiff_", $self)
+ or return undef;
+ $self->_set_opts(\%input, "exif_", $self)
+ or return undef;
+
+ if (defined $input{class} && $input{class} eq 'fax') {
+ if (!i_writetiff_wiol_faxable($self->{IMG}, $IO, $input{fax_fine})) {
+ $self->{ERRSTR}='Could not write to buffer';
+ return undef;
+ }
+ } else {
+ if (!i_writetiff_wiol($self->{IMG}, $IO)) {
+ $self->{ERRSTR}='Could not write to buffer';
+ return undef;
+ }
+ }
+ } elsif ( $input{'type'} eq 'pnm' ) {
+ $self->_set_opts(\%input, "pnm_", $self)
+ or return undef;
+ if ( ! i_writeppm_wiol($self->{IMG},$IO) ) {
+ $self->{ERRSTR}='unable to write pnm image';
+ return undef;
+ }
+ $self->{DEBUG} && print "writing a pnm file\n";
+ } elsif ( $input{'type'} eq 'raw' ) {
+ $self->_set_opts(\%input, "raw_", $self)
+ or return undef;
+ if ( !i_writeraw_wiol($self->{IMG},$IO) ) {
+ $self->{ERRSTR}='unable to write raw image';
+ return undef;
+ }
+ $self->{DEBUG} && print "writing a raw file\n";
+ } elsif ( $input{'type'} eq 'png' ) {
+ $self->_set_opts(\%input, "png_", $self)
+ or return undef;
+ if ( !i_writepng_wiol($self->{IMG}, $IO) ) {
+ $self->{ERRSTR}='unable to write png image';
+ return undef;
+ }
+ $self->{DEBUG} && print "writing a png file\n";
+ } elsif ( $input{'type'} eq 'jpeg' ) {
+ $self->_set_opts(\%input, "jpeg_", $self)
+ or return undef;
+ $self->_set_opts(\%input, "exif_", $self)
+ or return undef;
+ if ( !i_writejpeg_wiol($self->{IMG}, $IO, $input{jpegquality})) {
+ $self->{ERRSTR} = $self->_error_as_msg();
+ return undef;
+ }
+ $self->{DEBUG} && print "writing a jpeg file\n";
+ } elsif ( $input{'type'} eq 'bmp' ) {
+ $self->_set_opts(\%input, "bmp_", $self)
+ or return undef;
+ if ( !i_writebmp_wiol($self->{IMG}, $IO) ) {
+ $self->{ERRSTR}='unable to write bmp image';
+ return undef;
+ }
+ $self->{DEBUG} && print "writing a bmp file\n";
+ } elsif ( $input{'type'} eq 'tga' ) {
+ $self->_set_opts(\%input, "tga_", $self)
+ or return undef;
+
+ if ( !i_writetga_wiol($self->{IMG}, $IO, $input{wierdpack}, $input{compress}, $input{idstring}) ) {
+ $self->{ERRSTR}=$self->_error_as_msg();
+ return undef;
+ }
+ $self->{DEBUG} && print "writing a tga file\n";
+ } elsif ( $input{'type'} eq 'gif' ) {
+ $self->_set_opts(\%input, "gif_", $self)
+ or return undef;
+ # compatibility with the old interfaces
+ if ($input{gifquant} eq 'lm') {
+ $input{make_colors} = 'addi';
+ $input{translate} = 'perturb';
+ $input{perturb} = $input{lmdither};
+ } elsif ($input{gifquant} eq 'gen') {
+ # just pass options through
+ } else {
+ $input{make_colors} = 'webmap'; # ignored
+ $input{translate} = 'giflib';
+ }
+ $rc = i_writegif_wiol($IO, \%input, $self->{IMG});
+ }
+
+ if (exists $input{'data'}) {
+ my $data = io_slurp($IO);
+ if (!$data) {
+ $self->{ERRSTR}='Could not slurp from buffer';
+ return undef;
+ }
+ ${$input{data}} = $data;
+ }
+ return $self;
+ }
+
+ return $self;
+}
+
+sub write_multi {
+ my ($class, $opts, @images) = @_;
+
+ if (!$opts->{'type'} && $opts->{'file'}) {
+ $opts->{'type'} = $FORMATGUESS->($opts->{'file'});
+ }
+ unless ($opts->{'type'}) {
+ $class->_set_error('type parameter missing and not possible to guess from extension');
+ return;
+ }
+ # translate to ImgRaw
+ if (grep !UNIVERSAL::isa($_, 'Imager') || !$_->{IMG}, @images) {
+ $class->_set_error('Usage: Imager->write_multi({ options }, @images)');
+ return 0;
+ }
+ $class->_set_opts($opts, "i_", @images)
+ or return;
+ my @work = map $_->{IMG}, @images;
+ my ($IO, $file) = $class->_get_writer_io($opts, $opts->{'type'})
+ or return undef;
+ if ($opts->{'type'} eq 'gif') {
+ $class->_set_opts($opts, "gif_", @images)
+ or return;
+ my $gif_delays = $opts->{gif_delays};
+ local $opts->{gif_delays} = $gif_delays;
+ if ($opts->{gif_delays} && !ref $opts->{gif_delays}) {
+ # assume the caller wants the same delay for each frame
+ $opts->{gif_delays} = [ ($gif_delays) x @images ];
+ }
+ my $res = i_writegif_wiol($IO, $opts, @work);
+ $res or $class->_set_error($class->_error_as_msg());
+ return $res;
+ }
+ elsif ($opts->{'type'} eq 'tiff') {
+ $class->_set_opts($opts, "tiff_", @images)
+ or return;
+ $class->_set_opts($opts, "exif_", @images)
+ or return;
+ my $res;
+ $opts->{fax_fine} = 1 unless exists $opts->{fax_fine};
+ if ($opts->{'class'} && $opts->{'class'} eq 'fax') {
+ $res = i_writetiff_multi_wiol_faxable($IO, $opts->{fax_fine}, @work);
+ }
+ else {
+ $res = i_writetiff_multi_wiol($IO, @work);
+ }
+ $res or $class->_set_error($class->_error_as_msg());
+ return $res;
+ }
+ else {
+ $ERRSTR = "Sorry, write_multi doesn't support $opts->{'type'} yet";
+ return 0;
+ }
+}
+
+# read multiple images from a file
+sub read_multi {
+ my ($class, %opts) = @_;
+
+ if ($opts{file} && !exists $opts{'type'}) {
+ # guess the type
+ my $type = $FORMATGUESS->($opts{file});
+ $opts{'type'} = $type;
+ }
+ unless ($opts{'type'}) {
+ $ERRSTR = "No type parameter supplied and it couldn't be guessed";
+ return;
+ }
+
+ my ($IO, $file) = $class->_get_reader_io(\%opts, $opts{'type'})
+ or return;
+ if ($opts{'type'} eq 'gif') {
+ my @imgs;
+ @imgs = i_readgif_multi_wiol($IO);
+ if (@imgs) {
+ return map {
+ bless { IMG=>$_, DEBUG=>$DEBUG, ERRSTR=>undef }, 'Imager'
+ } @imgs;
+ }
+ else {
+ $ERRSTR = _error_as_msg();
+ return;
+ }
+ }
+ elsif ($opts{'type'} eq 'tiff') {
+ my @imgs = i_readtiff_multi_wiol($IO, -1);
+ if (@imgs) {
+ return map {
+ bless { IMG=>$_, DEBUG=>$DEBUG, ERRSTR=>undef }, 'Imager'
+ } @imgs;
+ }
+ else {
+ $ERRSTR = _error_as_msg();
+ return;
+ }
+ }
+
+ $ERRSTR = "Cannot read multiple images from $opts{'type'} files";
+ return;
+}
+
+# Destroy an Imager object
+
+sub DESTROY {
+ my $self=shift;
+ # delete $instances{$self};
+ if (defined($self->{IMG})) {
+ # the following is now handled by the XS DESTROY method for
+ # Imager::ImgRaw object
+ # Re-enabling this will break virtual images
+ # tested for in t/t020masked.t
+ # i_img_destroy($self->{IMG});
+ undef($self->{IMG});
+ } else {
+# print "Destroy Called on an empty image!\n"; # why did I put this here??
+ }
+}
+
+# Perform an inplace filter of an image
+# that is the image will be overwritten with the data
+
+sub filter {
+ my $self=shift;
+ my %input=@_;
+ my %hsh;
+ unless ($self->{IMG}) { $self->{ERRSTR}='empty input image'; return undef; }
+
+ if (!$input{'type'}) { $self->{ERRSTR}='type parameter missing'; return undef; }
+
+ if ( (grep { $_ eq $input{'type'} } keys %filters) != 1) {
+ $self->{ERRSTR}='type parameter not matching any filter'; return undef;
+ }
+
+ if ($filters{$input{'type'}}{names}) {
+ my $names = $filters{$input{'type'}}{names};
+ for my $name (keys %$names) {
+ if (defined $input{$name} && exists $names->{$name}{$input{$name}}) {
+ $input{$name} = $names->{$name}{$input{$name}};
+ }
+ }
+ }
+ if (defined($filters{$input{'type'}}{defaults})) {
+ %hsh=('image',$self->{IMG},%{$filters{$input{'type'}}{defaults}},%input);
+ } else {
+ %hsh=('image',$self->{IMG},%input);
+ }
+
+ my @cs=@{$filters{$input{'type'}}{callseq}};
+
+ for(@cs) {
+ if (!defined($hsh{$_})) {
+ $self->{ERRSTR}="missing parameter '$_' for filter ".$input{'type'}; return undef;
}
}
- &{$filters{$input{type}}{callsub}}(%hsh);
+ &{$filters{$input{'type'}}{callsub}}(%hsh);
my @b=keys %hsh;
sub scale {
my $self=shift;
- my %opts=(scalefactor=>0.5,type=>'max',qtype=>'normal',@_);
+ my %opts=(scalefactor=>0.5,'type'=>'max',qtype=>'normal',@_);
my $img = Imager->new();
my $tmp = Imager->new();
unless ($self->{IMG}) { $self->{ERRSTR}='empty input image'; return undef; }
- if ($opts{xpixels} and $opts{ypixels} and $opts{type}) {
+ if ($opts{xpixels} and $opts{ypixels} and $opts{'type'}) {
my ($xpix,$ypix)=( $opts{xpixels}/$self->getwidth() , $opts{ypixels}/$self->getheight() );
- if ($opts{type} eq 'min') { $opts{scalefactor}=min($xpix,$ypix); }
- if ($opts{type} eq 'max') { $opts{scalefactor}=max($xpix,$ypix); }
+ if ($opts{'type'} eq 'min') { $opts{scalefactor}=min($xpix,$ypix); }
+ if ($opts{'type'} eq 'max') { $opts{scalefactor}=max($xpix,$ypix); }
} elsif ($opts{xpixels}) { $opts{scalefactor}=$opts{xpixels}/$self->getwidth(); }
elsif ($opts{ypixels}) { $opts{scalefactor}=$opts{ypixels}/$self->getheight(); }
{op=>'-',trans=>'Sub'},
{op=>'*',trans=>'Mult'},
{op=>'/',trans=>'Div'},
- {op=>'-',type=>'unary',trans=>'u-'},
+ {op=>'-','type'=>'unary',trans=>'u-'},
{op=>'**'},
- {op=>'func',type=>'unary'}],
+ {op=>'func','type'=>'unary'}],
'grouping'=>[qw( \( \) )],
'func'=>[qw( sin cos )],
'vars'=>[qw( x y )]
}
-{
- my $got_expr;
- sub transform2 {
- my ($opts, @imgs) = @_;
-
- if (!$got_expr) {
- # this is fairly big, delay loading it
- eval "use Imager::Expr";
- die $@ if $@;
- ++$got_expr;
- }
-
- $opts->{variables} = [ qw(x y) ];
- my ($width, $height) = @{$opts}{qw(width height)};
- if (@imgs) {
- $width ||= $imgs[0]->getwidth();
- $height ||= $imgs[0]->getheight();
- my $img_num = 1;
- for my $img (@imgs) {
- $opts->{constants}{"w$img_num"} = $img->getwidth();
- $opts->{constants}{"h$img_num"} = $img->getheight();
- $opts->{constants}{"cx$img_num"} = $img->getwidth()/2;
- $opts->{constants}{"cy$img_num"} = $img->getheight()/2;
- ++$img_num;
- }
+sub transform2 {
+ my ($opts, @imgs) = @_;
+
+ require "Imager/Expr.pm";
+
+ $opts->{variables} = [ qw(x y) ];
+ my ($width, $height) = @{$opts}{qw(width height)};
+ if (@imgs) {
+ $width ||= $imgs[0]->getwidth();
+ $height ||= $imgs[0]->getheight();
+ my $img_num = 1;
+ for my $img (@imgs) {
+ $opts->{constants}{"w$img_num"} = $img->getwidth();
+ $opts->{constants}{"h$img_num"} = $img->getheight();
+ $opts->{constants}{"cx$img_num"} = $img->getwidth()/2;
+ $opts->{constants}{"cy$img_num"} = $img->getheight()/2;
+ ++$img_num;
}
- if ($width) {
- $opts->{constants}{w} = $width;
- $opts->{constants}{cx} = $width/2;
- }
- else {
- $Imager::ERRSTR = "No width supplied";
- return;
- }
- if ($height) {
- $opts->{constants}{h} = $height;
- $opts->{constants}{cy} = $height/2;
- }
- else {
- $Imager::ERRSTR = "No height supplied";
- return;
- }
- my $code = Imager::Expr->new($opts);
- if (!$code) {
- $Imager::ERRSTR = Imager::Expr::error();
- return;
- }
-
- my $img = Imager->new();
- $img->{IMG} = i_transform2($opts->{width}, $opts->{height}, $code->code(),
- $code->nregs(), $code->cregs(),
- [ map { $_->{IMG} } @imgs ]);
- if (!defined $img->{IMG}) {
- $Imager::ERRSTR = "transform2 failed";
- return;
- }
-
- return $img;
}
-}
-
-
-
-
-
+ if ($width) {
+ $opts->{constants}{w} = $width;
+ $opts->{constants}{cx} = $width/2;
+ }
+ else {
+ $Imager::ERRSTR = "No width supplied";
+ return;
+ }
+ if ($height) {
+ $opts->{constants}{h} = $height;
+ $opts->{constants}{cy} = $height/2;
+ }
+ else {
+ $Imager::ERRSTR = "No height supplied";
+ return;
+ }
+ my $code = Imager::Expr->new($opts);
+ if (!$code) {
+ $Imager::ERRSTR = Imager::Expr::error();
+ return;
+ }
+ my $img = Imager->new();
+ $img->{IMG} = i_transform2($opts->{width}, $opts->{height}, $code->code(),
+ $code->nregs(), $code->cregs(),
+ [ map { $_->{IMG} } @imgs ]);
+ if (!defined $img->{IMG}) {
+ $Imager::ERRSTR = Imager->_error_as_msg();
+ return;
+ }
+ return $img;
+}
sub rubthrough {
my $self=shift;
unless ($self->{IMG}) { $self->{ERRSTR}='empty input image'; return undef; }
unless ($opts{src} && $opts{src}->{IMG}) { $self->{ERRSTR}='empty input image for source'; return undef; }
- i_rubthru($self->{IMG}, $opts{src}->{IMG}, $opts{tx},$opts{ty});
+ unless (i_rubthru($self->{IMG}, $opts{src}->{IMG}, $opts{tx},$opts{ty})) {
+ $self->{ERRSTR} = $self->_error_as_msg();
+ return undef;
+ }
return $self;
}
return ();
}
+sub rotate {
+ my $self = shift;
+ my %opts = @_;
+ if (defined $opts{right}) {
+ my $degrees = $opts{right};
+ if ($degrees < 0) {
+ $degrees += 360 * int(((-$degrees)+360)/360);
+ }
+ $degrees = $degrees % 360;
+ if ($degrees == 0) {
+ return $self->copy();
+ }
+ elsif ($degrees == 90 || $degrees == 180 || $degrees == 270) {
+ my $result = Imager->new();
+ if ($result->{IMG} = i_rotate90($self->{IMG}, $degrees)) {
+ return $result;
+ }
+ else {
+ $self->{ERRSTR} = $self->_error_as_msg();
+ return undef;
+ }
+ }
+ else {
+ $self->{ERRSTR} = "Parameter 'right' must be a multiple of 90 degrees";
+ return undef;
+ }
+ }
+ elsif (defined $opts{radians} || defined $opts{degrees}) {
+ my $amount = $opts{radians} || $opts{degrees} * 3.1415926535 / 180;
+
+ my $result = Imager->new;
+ if ($result->{IMG} = i_rotate_exact($self->{IMG}, $amount)) {
+ return $result;
+ }
+ else {
+ $self->{ERRSTR} = $self->_error_as_msg();
+ return undef;
+ }
+ }
+ else {
+ $self->{ERRSTR} = "Only the 'right' parameter is available";
+ return undef;
+ }
+}
+
+sub matrix_transform {
+ my $self = shift;
+ my %opts = @_;
+
+ if ($opts{matrix}) {
+ my $xsize = $opts{xsize} || $self->getwidth;
+ my $ysize = $opts{ysize} || $self->getheight;
+
+ my $result = Imager->new;
+ $result->{IMG} = i_matrix_transform($self->{IMG}, $xsize, $ysize,
+ $opts{matrix})
+ or return undef;
+
+ return $result;
+ }
+ else {
+ $self->{ERRSTR} = "matrix parameter required";
+ return undef;
+ }
+}
+# blame Leolo :)
+*yatf = \&matrix_transform;
# These two are supported for legacy code only
sub i_color_new {
- return Imager::Color->new($_[0], $_[1], $_[2], $_[3]);
+ return Imager::Color->new(@_);
}
sub i_color_set {
- return Imager::Color::set($_[0], $_[1], $_[2], $_[3], $_[4]);
+ return Imager::Color::set(@_);
}
-
-
# Draws a box between the specified corner points.
-
sub box {
my $self=shift;
unless ($self->{IMG}) { $self->{ERRSTR}='empty input image'; return undef; }
$opts{'ymax'} = max($opts{'box'}->[1],$opts{'box'}->[3]);
}
- if ($opts{filled}) { i_box_filled($self->{IMG},$opts{xmin},$opts{ymin},$opts{xmax},$opts{ymax},$opts{color}); }
- else { i_box($self->{IMG},$opts{xmin},$opts{ymin},$opts{xmax},$opts{ymax},$opts{color}); }
+ if ($opts{filled}) {
+ my $color = _color($opts{'color'});
+ unless ($color) {
+ $self->{ERRSTR} = $Imager::ERRSTR;
+ return;
+ }
+ i_box_filled($self->{IMG},$opts{xmin},$opts{ymin},$opts{xmax},
+ $opts{ymax}, $color);
+ }
+ elsif ($opts{fill}) {
+ unless (UNIVERSAL::isa($opts{fill}, 'Imager::Fill')) {
+ # assume it's a hash ref
+ require 'Imager/Fill.pm';
+ unless ($opts{fill} = Imager::Fill->new(%{$opts{fill}})) {
+ $self->{ERRSTR} = $Imager::ERRSTR;
+ return undef;
+ }
+ }
+ i_box_cfill($self->{IMG},$opts{xmin},$opts{ymin},$opts{xmax},
+ $opts{ymax},$opts{fill}{fill});
+ }
+ else {
+ my $color = _color($opts{'color'});
+ unless ($color) {
+ $self->{ERRSTR} = $Imager::ERRSTR;
+ return;
+ }
+ i_box($self->{IMG},$opts{xmin},$opts{ymin},$opts{xmax},$opts{ymax},
+ $color);
+ }
return $self;
}
'x'=>$self->getwidth()/2,
'y'=>$self->getheight()/2,
'd1'=>0, 'd2'=>361, @_);
- i_arc($self->{IMG},$opts{'x'},$opts{'y'},$opts{'r'},$opts{'d1'},$opts{'d2'},$opts{'color'});
+ if ($opts{fill}) {
+ unless (UNIVERSAL::isa($opts{fill}, 'Imager::Fill')) {
+ # assume it's a hash ref
+ require 'Imager/Fill.pm';
+ unless ($opts{fill} = Imager::Fill->new(%{$opts{fill}})) {
+ $self->{ERRSTR} = $Imager::ERRSTR;
+ return;
+ }
+ }
+ i_arc_cfill($self->{IMG},$opts{'x'},$opts{'y'},$opts{'r'},$opts{'d1'},
+ $opts{'d2'}, $opts{fill}{fill});
+ }
+ else {
+ my $color = _color($opts{'color'});
+ unless ($color) {
+ $self->{ERRSTR} = $Imager::ERRSTR;
+ return;
+ }
+ if ($opts{d1} == 0 && $opts{d2} == 361 && $opts{aa}) {
+ i_circle_aa($self->{IMG}, $opts{'x'}, $opts{'y'}, $opts{'r'},
+ $color);
+ }
+ else {
+ if ($opts{'d1'} <= $opts{'d2'}) {
+ i_arc($self->{IMG},$opts{'x'},$opts{'y'},$opts{'r'},
+ $opts{'d1'}, $opts{'d2'}, $color);
+ }
+ else {
+ i_arc($self->{IMG},$opts{'x'},$opts{'y'},$opts{'r'},
+ $opts{'d1'}, 361, $color);
+ i_arc($self->{IMG},$opts{'x'},$opts{'y'},$opts{'r'},
+ 0, $opts{'d2'}, $color);
+ }
+ }
+ }
+
return $self;
}
-# Draws a line from one point to (but not including) the destination point
+# Draws a line from one point to the other
+# the endpoint is set if the endp parameter is set which it is by default.
+# to turn of the endpoint being set use endp=>0 when calling line.
sub line {
my $self=shift;
my $dflcl=i_color_new(0,0,0,0);
- my %opts=(color=>$dflcl,@_);
+ my %opts=(color=>$dflcl,
+ endp => 1,
+ @_);
unless ($self->{IMG}) { $self->{ERRSTR}='empty input image'; return undef; }
unless (exists $opts{x1} and exists $opts{y1}) { $self->{ERRSTR}='missing begining coord'; return undef; }
unless (exists $opts{x2} and exists $opts{y2}) { $self->{ERRSTR}='missing ending coord'; return undef; }
+ my $color = _color($opts{'color'});
+ unless ($color) {
+ $self->{ERRSTR} = $Imager::ERRSTR;
+ return;
+ }
+
+ $opts{antialias} = $opts{aa} if defined $opts{aa};
if ($opts{antialias}) {
- i_line_aa($self->{IMG},$opts{x1}, $opts{y1}, $opts{x2}, $opts{y2}, $opts{color});
+ i_line_aa($self->{IMG},$opts{x1}, $opts{y1}, $opts{x2}, $opts{y2},
+ $color, $opts{endp});
} else {
- i_draw($self->{IMG},$opts{x1}, $opts{y1}, $opts{x2}, $opts{y2}, $opts{color});
+ i_line($self->{IMG},$opts{x1}, $opts{y1}, $opts{x2}, $opts{y2},
+ $color, $opts{endp});
}
return $self;
}
# print Dumper(\@points);
+ my $color = _color($opts{'color'});
+ unless ($color) {
+ $self->{ERRSTR} = $Imager::ERRSTR;
+ return;
+ }
+ $opts{antialias} = $opts{aa} if defined $opts{aa};
if ($opts{antialias}) {
for $pt(@points) {
- if (defined($ls)) { i_line_aa($self->{IMG},$ls->[0],$ls->[1],$pt->[0],$pt->[1],$opts{color}); }
+ if (defined($ls)) {
+ i_line_aa($self->{IMG},$ls->[0],$ls->[1],$pt->[0],$pt->[1],$color, 1);
+ }
$ls=$pt;
}
} else {
for $pt(@points) {
- if (defined($ls)) { i_draw($self->{IMG},$ls->[0],$ls->[1],$pt->[0],$pt->[1],$opts{color}); }
+ if (defined($ls)) {
+ i_line($self->{IMG},$ls->[0],$ls->[1],$pt->[0],$pt->[1],$color,1);
+ }
$ls=$pt;
}
}
return $self;
}
-# this the multipoint bezier curve
+sub polygon {
+ my $self = shift;
+ my ($pt,$ls,@points);
+ my $dflcl = i_color_new(0,0,0,0);
+ my %opts = (color=>$dflcl, @_);
+
+ unless ($self->{IMG}) { $self->{ERRSTR}='empty input image'; return undef; }
+
+ if (exists($opts{points})) {
+ $opts{'x'} = [ map { $_->[0] } @{$opts{points}} ];
+ $opts{'y'} = [ map { $_->[1] } @{$opts{points}} ];
+ }
+
+ if (!exists $opts{'x'} or !exists $opts{'y'}) {
+ $self->{ERRSTR} = 'no points array, or x and y arrays.'; return undef;
+ }
+
+ if ($opts{'fill'}) {
+ unless (UNIVERSAL::isa($opts{'fill'}, 'Imager::Fill')) {
+ # assume it's a hash ref
+ require 'Imager/Fill.pm';
+ unless ($opts{'fill'} = Imager::Fill->new(%{$opts{'fill'}})) {
+ $self->{ERRSTR} = $Imager::ERRSTR;
+ return undef;
+ }
+ }
+ i_poly_aa_cfill($self->{IMG}, $opts{'x'}, $opts{'y'},
+ $opts{'fill'}{'fill'});
+ }
+ else {
+ my $color = _color($opts{'color'});
+ unless ($color) {
+ $self->{ERRSTR} = $Imager::ERRSTR;
+ return;
+ }
+ i_poly_aa($self->{IMG}, $opts{'x'}, $opts{'y'}, $color);
+ }
+
+ return $self;
+}
+
+
+# this the multipoint bezier curve
# this is here more for testing that actual usage since
# this is not a good algorithm. Usually the curve would be
# broken into smaller segments and each done individually.
return;
}
- i_bezier_multi($self->{IMG},$opts{'x'},$opts{'y'},$opts{'color'});
+ my $color = _color($opts{'color'});
+ unless ($color) {
+ $self->{ERRSTR} = $Imager::ERRSTR;
+ return;
+ }
+ i_bezier_multi($self->{IMG},$opts{'x'},$opts{'y'},$color);
return $self;
}
+sub flood_fill {
+ my $self = shift;
+ my %opts = ( color=>Imager::Color->new(255, 255, 255), @_ );
+ my $rc;
+
+ unless (exists $opts{'x'} && exists $opts{'y'}) {
+ $self->{ERRSTR} = "missing seed x and y parameters";
+ return undef;
+ }
+
+ if ($opts{fill}) {
+ unless (UNIVERSAL::isa($opts{fill}, 'Imager::Fill')) {
+ # assume it's a hash ref
+ require 'Imager/Fill.pm';
+ unless ($opts{fill} = Imager::Fill->new(%{$opts{fill}})) {
+ $self->{ERRSTR} = $Imager::ERRSTR;
+ return;
+ }
+ }
+ $rc = i_flood_cfill($self->{IMG}, $opts{'x'}, $opts{'y'}, $opts{fill}{fill});
+ }
+ else {
+ my $color = _color($opts{'color'});
+ unless ($color) {
+ $self->{ERRSTR} = $Imager::ERRSTR;
+ return;
+ }
+ $rc = i_flood_fill($self->{IMG}, $opts{'x'}, $opts{'y'}, $color);
+ }
+ if ($rc) { $self; } else { $self->{ERRSTR} = $self->_error_as_msg(); return (); }
+}
+
+sub setpixel {
+ my $self = shift;
+
+ my %opts = ( color=>$self->{fg} || NC(255, 255, 255), @_);
+
+ unless (exists $opts{'x'} && exists $opts{'y'}) {
+ $self->{ERRSTR} = 'missing x and y parameters';
+ return undef;
+ }
+
+ my $x = $opts{'x'};
+ my $y = $opts{'y'};
+ my $color = _color($opts{color})
+ or return undef;
+ if (ref $x && ref $y) {
+ unless (@$x == @$y) {
+ $self->{ERRSTR} = 'length of x and y mismatch';
+ return undef;
+ }
+ if ($color->isa('Imager::Color')) {
+ for my $i (0..$#{$opts{'x'}}) {
+ i_ppix($self->{IMG}, $x->[$i], $y->[$i], $color);
+ }
+ }
+ else {
+ for my $i (0..$#{$opts{'x'}}) {
+ i_ppixf($self->{IMG}, $x->[$i], $y->[$i], $color);
+ }
+ }
+ }
+ else {
+ if ($color->isa('Imager::Color')) {
+ i_ppix($self->{IMG}, $x, $y, $color);
+ }
+ else {
+ i_ppixf($self->{IMG}, $x, $y, $color);
+ }
+ }
+
+ $self;
+}
+
+sub getpixel {
+ my $self = shift;
+
+ my %opts = ( "type"=>'8bit', @_);
+
+ unless (exists $opts{'x'} && exists $opts{'y'}) {
+ $self->{ERRSTR} = 'missing x and y parameters';
+ return undef;
+ }
+
+ my $x = $opts{'x'};
+ my $y = $opts{'y'};
+ if (ref $x && ref $y) {
+ unless (@$x == @$y) {
+ $self->{ERRSTR} = 'length of x and y mismatch';
+ return undef;
+ }
+ my @result;
+ if ($opts{"type"} eq '8bit') {
+ for my $i (0..$#{$opts{'x'}}) {
+ push(@result, i_get_pixel($self->{IMG}, $x->[$i], $y->[$i]));
+ }
+ }
+ else {
+ for my $i (0..$#{$opts{'x'}}) {
+ push(@result, i_gpixf($self->{IMG}, $x->[$i], $y->[$i]));
+ }
+ }
+ return wantarray ? @result : \@result;
+ }
+ else {
+ if ($opts{"type"} eq '8bit') {
+ return i_get_pixel($self->{IMG}, $x, $y);
+ }
+ else {
+ return i_gpixf($self->{IMG}, $x, $y);
+ }
+ }
+
+ $self;
+}
+
# make an identity matrix of the given size
sub _identity {
my ($size) = @_;
}
+# general function to map an image through lookup tables
+
+sub map {
+ my ($self, %opts) = @_;
+ my @chlist = qw( red green blue alpha );
+
+ if (!exists($opts{'maps'})) {
+ # make maps from channel maps
+ my $chnum;
+ for $chnum (0..$#chlist) {
+ if (exists $opts{$chlist[$chnum]}) {
+ $opts{'maps'}[$chnum] = $opts{$chlist[$chnum]};
+ } elsif (exists $opts{'all'}) {
+ $opts{'maps'}[$chnum] = $opts{'all'};
+ }
+ }
+ }
+ if ($opts{'maps'} and $self->{IMG}) {
+ i_map($self->{IMG}, $opts{'maps'} );
+ }
+ return $self;
+}
+
+sub difference {
+ my ($self, %opts) = @_;
+
+ defined $opts{mindist} or $opts{mindist} = 0;
+
+ defined $opts{other}
+ or return $self->_set_error("No 'other' parameter supplied");
+ defined $opts{other}{IMG}
+ or return $self->_set_error("No image data in 'other' image");
+
+ $self->{IMG}
+ or return $self->_set_error("No image data");
+
+ my $result = Imager->new;
+ $result->{IMG} = i_diff_image($self->{IMG}, $opts{other}{IMG},
+ $opts{mindist})
+ or return $self->_set_error($self->_error_as_msg());
+
+ return $result;
+}
+
# destructive border - image is shrunk by one pixel all around
sub border {
sub getcolorcount {
my $self=shift;
- my %opts=(maxcolors=>2**30,@_);
+ my %opts=('maxcolors'=>2**30,@_);
if (!defined($self->{IMG})) { $self->{ERRSTR}='image is empty'; return undef; }
my $rc=i_count_colors($self->{IMG},$opts{'maxcolors'});
return ($rc==-1? undef : $rc);
return;
}
- my $aa=1;
- my $font=$input{'font'};
- my $align=$font->{'align'} unless exists $input{'align'};
- my $color=$input{'color'} || $font->{'color'};
- my $size=$input{'size'} || $font->{'size'};
-
- if (!defined($size)) { $self->{ERRSTR}='No size parameter and no default in font'; return undef; }
-
- $aa=$font->{'aa'} if exists $font->{'aa'};
- $aa=$input{'aa'} if exists $input{'aa'};
-
-
-
-# unless($font->can('text')) {
-# $self->{ERRSTR}="font is unable to do what we need";
-# return;
-# }
-
-# use Data::Dumper;
-# warn Dumper($font);
-
-# print "Channel=".$input{'channel'}."\n";
-
- if ( $font->{'type'} eq 't1' ) {
- if ( exists $input{'channel'} ) {
- Imager::Font::t1_set_aa_level($aa);
- i_t1_cp($self->{IMG},$input{'x'},$input{'y'},
- $input{'channel'},$font->{'id'},$size,
- $input{'string'},length($input{'string'}),1);
- } else {
- Imager::Font::t1_set_aa_level($aa);
- i_t1_text($self->{IMG},$input{'x'},$input{'y'},
- $color,$font->{'id'},$size,
- $input{'string'},length($input{'string'}),1);
- }
- }
-
- if ( $font->{'type'} eq 'tt' ) {
- if ( exists $input{'channel'} ) {
- i_tt_cp($font->{'id'},$self->{IMG},$input{'x'},$input{'y'},$input{'channel'},
- $size,$input{'string'},length($input{'string'}),$aa);
- } else {
- i_tt_text($font->{'id'},$self->{IMG},$input{'x'},$input{'y'},$color,$size,
- $input{'string'},length($input{'string'}),$aa);
- }
+ unless ($input{font}->draw(image=>$self, %input)) {
+ $self->{ERRSTR} = $self->_error_as_msg();
+ return;
}
return $self;
}
-
-
-
-
# Shortcuts that can be exported
sub newcolor { Imager::Color->new(@_); }
#### Utility routines
-sub errstr { $_[0]->{ERRSTR} }
-
-
-
+sub errstr {
+ ref $_[0] ? $_[0]->{ERRSTR} : $ERRSTR
+}
+sub _set_error {
+ my ($self, $msg) = @_;
+ if (ref $self) {
+ $self->{ERRSTR} = $msg;
+ }
+ else {
+ $ERRSTR = $msg;
+ }
+ return;
+}
# Default guess for the type of an image from extension
return 'jpeg' if ($ext =~ m/^jpe?g$/);
return 'pnm' if ($ext =~ m/^p[pgb]m$/);
return 'png' if ($ext eq "png");
+ return 'bmp' if ($ext eq "bmp" || $ext eq "dib");
+ return 'tga' if ($ext eq "tga");
+ return 'rgb' if ($ext eq "rgb");
return 'gif' if ($ext eq "gif");
+ return 'raw' if ($ext eq "raw");
return ();
}
if (/^\004\004/) {
@sar=split(/\034\002/);
foreach $item (@sar) {
- if ($item =~ m/^x/) {
+ if ($item =~ m/^x/) {
$caption=&clean($item);
$i++;
}
- if ($item =~ m/^P/) {
+ if ($item =~ m/^P/) {
$photogr=&clean($item);
$i++;
}
- if ($item =~ m/^i/) {
+ if ($item =~ m/^i/) {
$headln=&clean($item);
$i++;
}
- if ($item =~ m/^n/) {
+ if ($item =~ m/^n/) {
$credit=&clean($item);
$i++;
}
return (caption=>$caption,photogr=>$photogr,headln=>$headln,credit=>$credit);
}
-
-
-
-
-
# Autoload methods go after =cut, and are processed by the autosplit program.
1;
=head1 SYNOPSIS
- use Imager qw(init);
-
- init();
- $img = Imager->new();
- $img->open(file=>'image.ppm',type=>'pnm')
- || print "failed: ",$img->{ERRSTR},"\n";
- $scaled=$img->scale(xpixels=>400,ypixels=>400);
- $scaled->write(file=>'sc_image.ppm',type=>'pnm')
- || print "failed: ",$scaled->{ERRSTR},"\n";
-
-=head1 DESCRIPTION
-
-Imager is a module for creating and altering images - It is not meant
-as a replacement or a competitor to ImageMagick or GD. Both are
-excellent packages and well supported.
+ # Thumbnail example
-=head2 API
-
-Almost all functions take the parameters in the hash fashion.
-Example:
-
- $img->open(file=>'lena.png',type=>'png');
-
-or just:
-
- $img->open(file=>'lena.png');
+ #!/usr/bin/perl -w
+ use strict;
+ use Imager;
-=head2 Basic concept
+ die "Usage: thumbmake.pl filename\n" if !-f $ARGV[0];
+ my $file = shift;
-An Image object is created with C<$img = Imager-E<gt>new()> Should
-this fail for some reason an explanation can be found in
-C<$Imager::ERRSTR> usually error messages are stored in
-C<$img-E<gt>{ERRSTR}>, but since no object is created this is the only
-way to give back errors. C<$Imager::ERRSTR> is also used to report
-all errors not directly associated with an image object. Examples:
+ my $format;
- $img=Imager->new(); # This is an empty image (size is 0 by 0)
- $img->open(file=>'lena.png',type=>'png'); # initializes from file
+ my $img = Imager->new();
+ $img->open(file=>$file) or die $img->errstr();
-or if you want to create an empty image:
+ $file =~ s/\.[^.]*$//;
- $img=Imager->new(xsize=>400,ysize=>300,channels=>4);
+ # Create smaller version
+ my $thumb = $img->scale(scalefactor=>.3);
-This example creates a completely black image of width 400 and
-height 300 and 4 channels.
-
-If you have an existing image, use img_set() to change it's dimensions
-- this will destroy any existing image data:
-
- $img->img_set(xsize=>500, ysize=>500, channels=>4);
-
-Color objects are created by calling the Imager::Color->new()
-method:
-
- $color = Imager::Color->new($red, $green, $blue);
- $color = Imager::Color->new($red, $green, $blue, $alpha);
- $color = Imager::Color->new("#C0C0FF"); # html color specification
-
-This object can then be passed to functions that require a color parameter.
-
-Coordinates in Imager have the origin in the upper left corner. The
-horizontal coordinate increases to the right and the vertical
-downwards.
-
-=head2 Reading and writing images
-
-C<$img-E<gt>read()> generally takes two parameters, 'file' and 'type'.
-If the type of the file can be determined from the suffix of the file
-it can be omitted. Format dependant parameters are: For images of
-type 'raw' two extra parameters are needed 'xsize' and 'ysize', if the
-'channel' parameter is omitted for type 'raw' it is assumed to be 3.
-gif and png images might have a palette are converted to truecolor bit
-when read. Alpha channel is preserved for png images irregardless of
-them being in RGB or gray colorspace. Similarly grayscale jpegs are
-one channel images after reading them. For jpeg images the iptc
-header information (stored in the APP13 header) is avaliable to some
-degree. You can get the raw header with C<$img-E<gt>{IPTCRAW}>, but
-you can also retrieve the most basic information with
-C<%hsh=$img-E<gt>parseiptc()> as always patches are welcome. pnm has no
-extra options. Examples:
-
- $img = Imager->new();
- $img->read(file=>"cover.jpg") or die $img->errstr; # gets type from name
-
- $img = Imager->new();
- { local(*FH,$/); open(FH,"file.gif") or die $!; $a=<FH>; }
- $img->read(data=>$a,type=>'gif') or die $img->errstr;
-
-The second example shows how to read an image from a scalar, this is
-usefull if your data originates from somewhere else than a filesystem
-such as a database over a DBI connection.
-
-When writing to a tiff image file you can also specify the 'class'
-parameter, which can currently take a single value, "fax". If class
-is set to fax then a tiff image which should be suitable for faxing
-will be written. For the best results start with a grayscale image.
-By default the image is written at fine resolution you can override
-this by setting the "fax_fine" parameter to 0.
-
-If you are reading from a gif image file, you can supply a 'colors'
-parameter which must be a reference to a scalar. The referenced
-scalar will receive an array reference which contains the colors, each
-represented as an Imager::Color object.
-
-If you already have an open file handle, for example a socket or a
-pipe, you can specify the 'fd' parameter instead of supplying a
-filename. Please be aware that you need to use fileno() to retrieve
-the file descriptor for the file:
-
- $img->read(fd=>fileno(FILE), type=>'gif') or die $img->errstr;
-
-For writing using the 'fd' option you will probably want to set $| for
-that descriptor, since the writes to the file descriptor bypass Perl's
-(or the C libraries) buffering. Setting $| should avoid out of order
-output.
-
-*Note that load() is now an alias for read but will be removed later*
-
-C<$img-E<gt>write> has the same interface as C<read()>. The earlier
-comments on C<read()> for autodetecting filetypes apply. For jpegs
-quality can be adjusted via the 'jpegquality' parameter (0-100). The
-number of colorplanes in gifs are set with 'gifplanes' and should be
-between 1 (2 color) and 8 (256 colors). It is also possible to choose
-between two quantizing methods with the parameter 'gifquant'. If set
-to mc it uses the mediancut algorithm from either giflibrary. If set
-to lm it uses a local means algorithm. It is then possible to give
-some extra settings. lmdither is the dither deviation amount in pixels
-(manhattan distance). lmfixed can be an array ref who holds an array
-of Imager::Color objects. Note that the local means algorithm needs
-much more cpu time but also gives considerable better results than the
-median cut algorithm.
-
-Currently just for gif files, you can specify various options for the
-conversion from Imager's internal RGB format to the target's indexed
-file format. If you set the gifquant option to 'gen', you can use the
-options specified under L<Quantization options>.
-
-To see what Imager is compiled to support the following code snippet
-is sufficient:
+ # Autostretch individual channels
+ $thumb->filter(type=>'autolevels');
- use Imager;
- print "@{[keys %Imager::formats]}";
+ # try to save in one of these formats
+ SAVE:
-When reading raw images you need to supply the width and height of the
-image in the xsize and ysize options:
+ for $format ( qw( png gif jpg tiff ppm ) ) {
+ # Check if given format is supported
+ if ($Imager::formats{$format}) {
+ $file.="_low.$format";
+ print "Storing image as: $file\n";
+ $thumb->write(file=>$file) or
+ die $thumb->errstr;
+ last SAVE;
+ }
+ }
- $img->read(file=>'foo.raw', xsize=>100, ysize=>100)
- or die "Cannot read raw image\n";
-If your input file has more channels than you want, or (as is common),
-junk in the fourth channel, you can use the datachannels and
-storechannels options to control the number of channels in your input
-file and the resulting channels in your image. For example, if your
-input image uses 32-bits per pixel with red, green, blue and junk
-values for each pixel you could do:
- $img->read(file=>'foo.raw', xsize=>100, ysize=>100, datachannels=>4,
- storechannels=>3)
- or die "Cannot read raw image\n";
-Normally the raw image is expected to have the value for channel 1
-immediately following channel 0 and channel 2 immediately following
-channel 1 for each pixel. If your input image has all the channel 0
-values for the first line of the image, followed by all the channel 1
-values for the first line and so on, you can use the interleave option:
+=head1 DESCRIPTION
- $img->read(file=>'foo.raw', xsize=100, ysize=>100, interleave=>1)
- or die "Cannot read raw image\n";
+Imager is a module for creating and altering images. It can read and
+write various image formats, draw primitive shapes like lines,and
+polygons, blend multiple images together in various ways, scale, crop,
+render text and more.
-=head2 Multi-image files
+=head2 Overview of documentation
-Currently just for gif files, you can create files that contain more
-than one image.
+=over
-To do this:
+=item Imager
- Imager->write_multi(\%opts, @images)
+This document - Synopsis Example, Table of Contents and Overview.
-Where %opts describes 4 possible types of outputs:
+=item Imager::ImageTypes
-=over 5
+Basics of constructing image objects with C<new()>:
+Direct type/virtual images, RGB(A)/paletted images, 8/16/double
+bits/channel, color maps, channel masks, image tags, color
+quantization. Also discusses basic image information methods.
-=item type
+=item Imager::Files
-This is C<gif> for gif animations.
+IO interaction, reading/writing images, format specific tags.
-=item callback
+=item Imager::Draw
-A code reference which is called with a single parameter, the data to
-be written. You can also specify $opts{maxbuffer} which is the
-maximum amount of data buffered. Note that there can be larger writes
-than this if the file library writes larger blocks. A smaller value
-maybe useful for writing to a socket for incremental display.
+Drawing Primitives, lines, boxes, circles, arcs, flood fill.
-=item fd
+=item Imager::Color
-The file descriptor to save the images to.
+Color specification.
-=item file
+=item Imager::Fill
-The name of the file to write to.
+Fill pattern specification.
-%opts may also include the keys from L<Gif options> and L<Quantization
-options>.
+=item Imager::Font
-=back
+General font rendering, bounding boxes and font metrics.
-You must also specify the file format using the 'type' option.
+=item Imager::Transformations
-The current aim is to support other multiple image formats in the
-future, such as TIFF, and to support reading multiple images from a
-single file.
+Copying, scaling, cropping, flipping, blending, pasting, convert and
+map.
-A simple example:
+=item Imager::Engines
- my @images;
- # ... code to put images in @images
- Imager->write_multi({type=>'gif',
- file=>'anim.gif',
- gif_delays=>[ (10) x @images ] },
- @images)
- or die "Oh dear!";
+Programmable transformations through C<transform()>, C<transform2()>
+and C<matrix_transform()>.
-=head2 Gif options
+=item Imager::Filters
-These options can be specified when calling write_multi() for gif
-files, when writing a single image with the gifquant option set to
-'gen', or for direct calls to i_writegif_gen and i_writegif_callback.
+Filters, sharpen, blur, noise, convolve etc. and filter plugins.
-Note that some viewers will ignore some of these options
-(gif_user_input in particular).
+=item Imager::Expr
-=over 4
+Expressions for evaluation engine used by transform2().
-=item gif_each_palette
+=item Imager::Matrix2d
-Each image in the gif file has it's own palette if this is non-zero.
-All but the first image has a local colour table (the first uses the
-global colour table.
+Helper class for affine transformations.
-=item interlace
+=item Imager::Fountain
-The images are written interlaced if this is non-zero.
+Helper for making gradient profiles.
-=item gif_delays
+=back
-A reference to an array containing the delays between images, in 1/100
-seconds.
-If you want the same delay for every frame you can simply set this to
-the delay in 1/100 seconds.
-=item gif_user_input
+=head2 Basic Overview
-A reference to an array contains user input flags. If the given flag
-is non-zero the image viewer should wait for input before displaying
-the next image.
+An Image object is created with C<$img = Imager-E<gt>new()>.
+Examples:
-=item gif_disposal
+ $img=Imager->new(); # create empty image
+ $img->open(file=>'lena.png',type=>'png') or # read image from file
+ die $img->errstr(); # give an explanation
+ # if something failed
-A reference to an array of image disposal methods. These define what
-should be done to the image before displaying the next one. These are
-integers, where 0 means unspecified, 1 means the image should be left
-in place, 2 means restore to background colour and 3 means restore to
-the previous value.
+or if you want to create an empty image:
-=item gif_tran_color
+ $img=Imager->new(xsize=>400,ysize=>300,channels=>4);
-A reference to an Imager::Color object, which is the colour to use for
-the palette entry used to represent transparency in the palette. You
-need to set the transp option (see L<Quantization options>) for this
-value to be used.
+This example creates a completely black image of width 400 and height
+300 and 4 channels.
-=item gif_positions
+When an operation fails which can be directly associated with an image
+the error message is stored can be retrieved with
+C<$img-E<gt>errstr()>.
-A reference to an array of references to arrays which represent screen
-positions for each image.
+In cases where no image object is associated with an operation
+C<$Imager::ERRSTR> is used to report errors not directly associated
+with an image object.
-=item gif_loop_count
+The C<Imager-><gt>new> method is described in detail in the
+Imager::ImageTypes manpage.
-If this is non-zero the Netscape loop extension block is generated,
-which makes the animation of the images repeat.
+=head1 SUPPORT
-This is currently unimplemented due to some limitations in giflib.
+You can ask for help, report bugs or express your undying love for
+Imager on the Imager-devel mailing list.
-=back
+To subscribe send a message with C<subscribe> in the body to:
-=head2 Quantization options
+ imager-devel+request@molar.is
-These options can be specified when calling write_multi() for gif
-files, when writing a single image with the gifquant option set to
-'gen', or for direct calls to i_writegif_gen and i_writegif_callback.
+or use the form at:
-=over 4
+ http://www.molar.is/en/lists/imager-devel/
+ (annonymous is temporarily off due to spam)
-=item colors
+where you can also find the mailing list archive.
-A arrayref of colors that are fixed. Note that some color generators
-will ignore this.
+If you're into IRC, you can typically find the developers in #Imager
+on irc.rhizomatic.net. As with any IRC channel, the participants
+could be occupied or asleep, so please be patient.
-=item transp
+=head1 BUGS
-The type of transparency processing to perform for images with an
-alpha channel where the output format does not have a proper alpha
-channel (eg. gif). This can be any of:
+Bugs are listed individually for relevant pod pages.
-=over 4
+=head1 AUTHOR
-=item none
+Arnar M. Hrafnkelsson (addi@imager.perl.org) and Tony Cook
+(tony@imager.perl.org) See the README for a complete list.
-No transparency processing is done. (default)
+=head1 SEE ALSO
-=item threshold
+perl(1), Imager::ImageTypes(3), Imager::Files(3), Imager::Draw(3),
+Imager::Color(3), Imager::Fill(3), Imager::Font(3),
+Imager::Transformations(3), Imager::Engines(3), Imager::Filters(3),
+Imager::Expr(3), Imager::Matrix2d(3), Imager::Fountain(3)
-Pixels more transparent that tr_threshold are rendered as transparent.
+Affix::Infix2Postfix(3), Parse::RecDescent(3)
+http://www.eecs.umich.edu/~addi/perl/Imager/
-=item errdiff
+=cut
-An error diffusion dither is done on the alpha channel. Note that
-this is independent of the translation performed on the colour
-channels, so some combinations may cause undesired artifacts.
-=item ordered
-The ordered dither specified by tr_orddith is performed on the alpha
-channel.
-=back
-
-This will only be used if the image has an alpha channel, and if there
-is space in the palette for a transparency colour.
-
-=item tr_threshold
-
-The highest alpha value at which a pixel will be made transparent when
-transp is 'threshold'. (0-255, default 127)
-
-=item tr_errdiff
-
-The type of error diffusion to perform on the alpha channel when
-transp is 'errdiff'. This can be any defined error diffusion type
-except for custom (see errdiff below).
-
-=item tr_orddith
-
-The type of ordered dither to perform on the alpha channel when transp
-is 'ordered'. Possible values are:
-
-=over 4
-
-=item random
-
-A semi-random map is used. The map is the same each time.
-
-=item dot8
-
-8x8 dot dither.
-
-=item dot4
-
-4x4 dot dither
-
-=item hline
-
-horizontal line dither.
-
-=item vline
-
-vertical line dither.
-
-=item "/line"
-
-=item slashline
-
-diagonal line dither
-
-=item '\line'
-
-=item backline
-
-diagonal line dither
-
-=item tiny
-
-dot matrix dither (currently the default). This is probably the best
-for displays (like web pages).
-
-=item custom
-
-A custom dither matrix is used - see tr_map
-
-=back
-
-=item tr_map
-
-When tr_orddith is custom this defines an 8 x 8 matrix of integers
-representing the transparency threshold for pixels corresponding to
-each position. This should be a 64 element array where the first 8
-entries correspond to the first row of the matrix. Values should be
-betweern 0 and 255.
-
-=item make_colors
-
-Defines how the quantization engine will build the palette(s).
-Currently this is ignored if 'translate' is 'giflib', but that may
-change. Possible values are:
-
-=over 4
-
-=item none
-
-Only colors supplied in 'colors' are used.
-
-=item webmap
-
-The web color map is used (need url here.)
-
-=item addi
-
-The original code for generating the color map (Addi's code) is used.
-
-=back
-
-Other methods may be added in the future.
-
-=item colors
-
-A arrayref containing Imager::Color objects, which represents the
-starting set of colors to use in translating the images. webmap will
-ignore this. The final colors used are copied back into this array
-(which is expanded if necessary.)
-
-=item max_colors
-
-The maximum number of colors to use in the image.
-
-=item translate
-
-The method used to translate the RGB values in the source image into
-the colors selected by make_colors. Note that make_colors is ignored
-whene translate is 'giflib'.
-
-Possible values are:
-
-=over 4
-
-=item giflib
-
-The giflib native quantization function is used.
-
-=item closest
-
-The closest color available is used.
-
-=item perturb
-
-The pixel color is modified by perturb, and the closest color is chosen.
-
-=item errdiff
-
-An error diffusion dither is performed.
-
-=back
-
-It's possible other transate values will be added.
-
-=item errdiff
-
-The type of error diffusion dither to perform. These values (except
-for custom) can also be used in tr_errdif.
-
-=over 4
-
-=item floyd
-
-Floyd-Steinberg dither
-
-=item jarvis
-
-Jarvis, Judice and Ninke dither
-
-=item stucki
-
-Stucki dither
-
-=item custom
-
-Custom. If you use this you must also set errdiff_width,
-errdiff_height and errdiff_map.
-
-=back
-
-=item errdiff_width
-
-=item errdiff_height
-
-=item errdiff_orig
-
-=item errdiff_map
-
-When translate is 'errdiff' and errdiff is 'custom' these define a
-custom error diffusion map. errdiff_width and errdiff_height define
-the size of the map in the arrayref in errdiff_map. errdiff_orig is
-an integer which indicates the current pixel position in the top row
-of the map.
-
-=item perturb
-
-When translate is 'perturb' this is the magnitude of the random bias
-applied to each channel of the pixel before it is looked up in the
-color table.
-
-=back
-
-=head2 Obtaining/setting attributes of images
-
-To get the size of an image in pixels the C<$img-E<gt>getwidth()> and
-C<$img-E<gt>getheight()> are used.
-
-To get the number of channels in
-an image C<$img-E<gt>getchannels()> is used. $img-E<gt>getmask() and
-$img-E<gt>setmask() are used to get/set the channel mask of the image.
-
- $mask=$img->getmask();
- $img->setmask(mask=>1+2); # modify red and green only
- $img->setmask(mask=>8); # modify alpha only
- $img->setmask(mask=>$mask); # restore previous mask
-
-The mask of an image describes which channels are updated when some
-operation is performed on an image. Naturally it is not possible to
-apply masks to operations like scaling that alter the dimensions of
-images.
-
-It is possible to have Imager find the number of colors in an image
-by using C<$img-E<gt>getcolorcount()>. It requires memory proportionally
-to the number of colors in the image so it is possible to have it
-stop sooner if you only need to know if there are more than a certain number
-of colors in the image. If there are more colors than asked for
-the function return undef. Examples:
-
- if (!defined($img->getcolorcount(maxcolors=>512)) {
- print "Less than 512 colors in image\n";
- }
-
-=head2 Drawing Methods
-
-IMPLEMENTATION MORE OR LESS DONE CHECK THE TESTS
-DOCUMENTATION OF THIS SECTION OUT OF SYNC
-
-It is possible to draw with graphics primitives onto images. Such
-primitives include boxes, arcs, circles and lines. A reference
-oriented list follows.
-
-Box:
- $img->box(color=>$blue,xmin=>10,ymin=>30,xmax=>200,ymax=>300,filled=>1);
-
-The above example calls the C<box> method for the image and the box
-covers the pixels with in the rectangle specified. If C<filled> is
-ommited it is drawn as an outline. If any of the edges of the box are
-ommited it will snap to the outer edge of the image in that direction.
-Also if a color is omitted a color with (255,255,255,255) is used
-instead.
-
-Arc:
- $img->arc(color=>$red, r=20, x=>200, y=>100, d1=>10, d2=>20 );
-
-This creates a filled red arc with a 'center' at (200, 100) and spans
-10 degrees and the slice has a radius of 20. SEE section on BUGS.
-
-Circle:
- $img->circle(color=>$green, r=50, x=>200, y=>100);
-
-This creates a green circle with its center at (200, 100) and has a
-radius of 20.
-
-Line:
- $img->line(color=>$green, x1=10, x2=>100,
- y1=>20, y2=>50, antialias=>1 );
-
-That draws an antialiased line from (10,100) to (20,50).
-
-Polyline:
- $img->polyline(points=>[[$x0,$y0],[$x1,$y1],[$x2,$y2]],color=>$red);
- $img->polyline(x=>[$x0,$x1,$x2], y=>[$y0,$y1,$y2], antialias=>1);
-
-Polyline is used to draw multilple lines between a series of points.
-The point set can either be specified as an arrayref to an array of
-array references (where each such array represents a point). The
-other way is to specify two array references.
-
-=head2 Text rendering
-
-Text rendering is described in the Imager::Font manpage.
-
-=head2 Image resizing
-
-To scale an image so porportions are maintained use the
-C<$img-E<gt>scale()> method. if you give either a xpixels or ypixels
-parameter they will determine the width or height respectively. If
-both are given the one resulting in a larger image is used. example:
-C<$img> is 700 pixels wide and 500 pixels tall.
-
- $img->scale(xpixels=>400); # 400x285
- $img->scale(ypixels=>400); # 560x400
-
- $img->scale(xpixels=>400,ypixels=>400); # 560x400
- $img->scale(xpixels=>400,ypixels=>400,type=>min); # 400x285
-
- $img->scale(scalefactor=>0.25); 175x125 $img->scale(); # 350x250
-
-if you want to create low quality previews of images you can pass
-C<qtype=E<gt>'preview'> to scale and it will use nearest neighbor
-sampling instead of filtering. It is much faster but also generates
-worse looking images - especially if the original has a lot of sharp
-variations and the scaled image is by more than 3-5 times smaller than
-the original.
-
-If you need to scale images per axis it is best to do it simply by
-calling scaleX and scaleY. You can pass either 'scalefactor' or
-'pixels' to both functions.
-
-Another way to resize an image size is to crop it. The parameters
-to crop are the edges of the area that you want in the returned image.
-If a parameter is omited a default is used instead.
-
- $newimg = $img->crop(left=>50, right=>100, top=>10, bottom=>100);
- $newimg = $img->crop(left=>50, top=>10, width=>50, height=>90);
- $newimg = $img->crop(left=>50, right=>100); # top
-
-You can also specify width and height parameters which will produce a
-new image cropped from the center of the input image, with the given
-width and height.
-
- $newimg = $img->crop(width=>50, height=>50);
-
-The width and height parameters take precedence over the left/right
-and top/bottom parameters respectively.
-
-=head2 Copying images
-
-To create a copy of an image use the C<copy()> method. This is usefull
-if you want to keep an original after doing something that changes the image
-inplace like writing text.
-
- $img=$orig->copy();
-
-To copy an image to onto another image use the C<paste()> method.
-
- $dest->paste(left=>40,top=>20,img=>$logo);
-
-That copies the entire C<$logo> image onto the C<$dest> image so that the
-upper left corner of the C<$logo> image is at (40,20).
-
-
-=head2 Flipping images
-
-An inplace horizontal or vertical flip is possible by calling the
-C<flip()> method. If the original is to be preserved it's possible to
-make a copy first. The only parameter it takes is the C<dir>
-parameter which can take the values C<h>, C<v>, C<vh> and C<hv>.
-
- $img->flip(dir=>"h"); # horizontal flip
- $img->flip(dir=>"vh"); # vertical and horizontal flip
- $nimg = $img->copy->flip(dir=>"v"); # make a copy and flip it vertically
-
-=head2 Blending Images
-
-To put an image or a part of an image directly
-into another it is best to call the C<paste()> method on the image you
-want to add to.
-
- $img->paste(img=>$srcimage,left=>30,top=>50);
-
-That will take paste C<$srcimage> into C<$img> with the upper
-left corner at (30,50). If no values are given for C<left>
-or C<top> they will default to 0.
-
-A more complicated way of blending images is where one image is
-put 'over' the other with a certain amount of opaqueness. The
-method that does this is rubthrough.
-
- $img->rubthrough(src=>$srcimage,tx=>30,ty=>50);
-
-That will take the image C<$srcimage> and overlay it with the
-upper left corner at (30,50). The C<$srcimage> must be a 4 channel
-image. The last channel is used as an alpha channel.
-
-
-=head2 Filters
-
-A special image method is the filter method. An example is:
-
- $img->filter(type=>'autolevels');
-
-This will call the autolevels filter. Here is a list of the filters
-that are always avaliable in Imager. This list can be obtained by
-running the C<filterlist.perl> script that comes with the module
-source.
-
- Filter Arguments
- turbnoise
- autolevels lsat(0.1) usat(0.1) skew(0)
- radnoise
- noise amount(3) subtype(0)
- contrast intensity
- hardinvert
- gradgen xo yo colors dist
-
-The default values are in parenthesis. All parameters must have some
-value but if a parameter has a default value it may be omitted when
-calling the filter function.
-
-FIXME: make a seperate pod for filters?
-
-=head2 Color transformations
-
-You can use the convert method to transform the color space of an
-image using a matrix. For ease of use some presets are provided.
-
-The convert method can be used to:
-
-=over 4
-
-=item *
-
-convert an RGB or RGBA image to grayscale.
-
-=item *
-
-convert a grayscale image to RGB.
-
-=item *
-
-extract a single channel from an image.
-
-=item *
-
-set a given channel to a particular value (or from another channel)
-
-=back
-
-The currently defined presets are:
-
-=over
-
-=item gray
-
-=item grey
-
-converts an RGBA image into a grayscale image with alpha channel, or
-an RGB image into a grayscale image without an alpha channel.
-
-This weights the RGB channels at 22.2%, 70.7% and 7.1% respectively.
-
-=item noalpha
-
-removes the alpha channel from a 2 or 4 channel image. An identity
-for other images.
-
-=item red
-
-=item channel0
-
-extracts the first channel of the image into a single channel image
-
-=item green
-
-=item channel1
-
-extracts the second channel of the image into a single channel image
-
-=item blue
-
-=item channel2
-
-extracts the third channel of the image into a single channel image
-
-=item alpha
-
-extracts the alpha channel of the image into a single channel image.
-
-If the image has 1 or 3 channels (assumed to be grayscale of RGB) then
-the resulting image will be all white.
-
-=item rgb
-
-converts a grayscale image to RGB, preserving the alpha channel if any
-
-=item addalpha
-
-adds an alpha channel to a grayscale or RGB image. Preserves an
-existing alpha channel for a 2 or 4 channel image.
-
-=back
-
-For example, to convert an RGB image into a greyscale image:
-
- $new = $img->convert(preset=>'grey'); # or gray
-
-or to convert a grayscale image to an RGB image:
-
- $new = $img->convert(preset=>'rgb');
-
-The presets aren't necessary simple constants in the code, some are
-generated based on the number of channels in the input image.
-
-If you want to perform some other colour transformation, you can use
-the 'matrix' parameter.
-
-For each output pixel the following matrix multiplication is done:
-
- channel[0] [ [ $c00, $c01, ... ] inchannel[0]
- [ ... ] = ... x [ ... ]
- channel[n-1] [ $cn0, ..., $cnn ] ] inchannel[max]
- 1
-
-So if you want to swap the red and green channels on a 3 channel image:
-
- $new = $img->convert(matrix=>[ [ 0, 1, 0 ],
- [ 1, 0, 0 ],
- [ 0, 0, 1 ] ]);
-
-or to convert a 3 channel image to greyscale using equal weightings:
-
- $new = $img->convert(matrix=>[ [ 0.333, 0.333, 0.334 ] ])
-
-=head2 Transformations
-
-Another special image method is transform. It can be used to generate
-warps and rotations and such features. It can be given the operations
-in postfix notation or the module Affix::Infix2Postfix can be used.
-Look in the test case t/t55trans.t for an example.
-
-transform() needs expressions (or opcodes) that determine the source
-pixel for each target pixel. Source expressions are infix expressions
-using any of the +, -, *, / or ** binary operators, the - unary
-operator, ( and ) for grouping and the sin() and cos() functions. The
-target pixel is input as the variables x and y.
-
-You specify the x and y expressions as xexpr and yexpr respectively.
-You can also specify opcodes directly, but that's magic deep enough
-that you can look at the source code.
-
-You can still use the transform() function, but the transform2()
-function is just as fast and is more likely to be enhanced and
-maintained.
-
-Later versions of Imager also support a transform2() class method
-which allows you perform a more general set of operations, rather than
-just specifying a spatial transformation as with the transform()
-method, you can also perform colour transformations, image synthesis
-and image combinations.
-
-transform2() takes an reference to an options hash, and a list of
-images to operate one (this list may be empty):
-
- my %opts;
- my @imgs;
- ...
- my $img = Imager::transform2(\%opts, @imgs)
- or die "transform2 failed: $Imager::ERRSTR";
-
-The options hash may define a transformation function, and optionally:
-
-=over 4
-
-=item *
-
-width - the width of the image in pixels. If this isn't supplied the
-width of the first input image is used. If there are no input images
-an error occurs.
-
-=item *
-
-height - the height of the image in pixels. If this isn't supplied
-the height of the first input image is used. If there are no input
-images an error occurs.
-
-=item *
-
-constants - a reference to hash of constants to define for the
-expression engine. Some extra constants are defined by Imager
-
-=back
-
-The tranformation function is specified using either the expr or
-rpnexpr member of the options.
-
-=over 4
-
-=item Infix expressions
-
-You can supply infix expressions to transform 2 with the expr keyword.
-
-$opts{expr} = 'return getp1(w-x, h-y)'
-
-The 'expression' supplied follows this general grammar:
-
- ( identifier '=' expr ';' )* 'return' expr
-
-This allows you to simplify your expressions using variables.
-
-A more complex example might be:
-
-$opts{expr} = 'pix = getp1(x,y); return if(value(pix)>0.8,pix*0.8,pix)'
-
-Currently to use infix expressions you must have the Parse::RecDescent
-module installed (available from CPAN). There is also what might be a
-significant delay the first time you run the infix expression parser
-due to the compilation of the expression grammar.
-
-=item Postfix expressions
-
-You can supply postfix or reverse-polish notation expressions to
-transform2() through the rpnexpr keyword.
-
-The parser for rpnexpr emulates a stack machine, so operators will
-expect to see their parameters on top of the stack. A stack machine
-isn't actually used during the image transformation itself.
-
-You can store the value at the top of the stack in a variable called
-foo using !foo and retrieve that value again using @foo. The !foo
-notation will pop the value from the stack.
-
-An example equivalent to the infix expression above:
-
- $opts{rpnexpr} = 'x y getp1 !pix @pix value 0.8 gt @pix 0.8 * @pix ifp'
-
-=back
-
-transform2() has a fairly rich range of operators.
-
-=over 4
-
-=item +, *, -, /, %, **
-
-multiplication, addition, subtraction, division, remainder and
-exponentiation. Multiplication, addition and subtraction can be used
-on colour values too - though you need to be careful - adding 2 white
-values together and multiplying by 0.5 will give you grey, not white.
-
-Division by zero (or a small number) just results in a large number.
-Modulo zero (or a small number) results in zero.
-
-=item sin(N), cos(N), atan2(y,x)
-
-Some basic trig functions. They work in radians, so you can't just
-use the hue values.
-
-=item distance(x1, y1, x2, y2)
-
-Find the distance between two points. This is handy (along with
-atan2()) for producing circular effects.
-
-=item sqrt(n)
-
-Find the square root. I haven't had much use for this since adding
-the distance() function.
-
-=item abs(n)
-
-Find the absolute value.
-
-=item getp1(x,y), getp2(x,y), getp3(x, y)
-
-Get the pixel at position (x,y) from the first, second or third image
-respectively. I may add a getpn() function at some point, but this
-prevents static checking of the instructions against the number of
-images actually passed in.
-
-=item value(c), hue(c), sat(c), hsv(h,s,v)
-
-Separates a colour value into it's value (brightness), hue (colour)
-and saturation elements. Use hsv() to put them back together (after
-suitable manipulation).
-
-=item red(c), green(c), blue(c), rgb(r,g,b)
-
-Separates a colour value into it's red, green and blue colours. Use
-rgb(r,g,b) to put it back together.
-
-=item int(n)
-
-Convert a value to an integer. Uses a C int cast, so it may break on
-large values.
-
-=item if(cond,ntrue,nfalse), if(cond,ctrue,cfalse)
-
-A simple (and inefficient) if function.
-
-=item <=,<,==,>=,>,!=
-
-Relational operators (typically used with if()). Since we're working
-with floating point values the equalities are 'near equalities' - an
-epsilon value is used.
-
-=item &&, ||, not(n)
-
-Basic logical operators.
-
-=back
-
-A few examples:
-
-=over 4
-
-=item rpnexpr=>'x 25 % 15 * y 35 % 10 * getp1 !pat x y getp1 !pix @pix sat 0.7 gt @pat @pix ifp'
-
-tiles a smaller version of the input image over itself where the colour has a saturation over 0.7.
-
-=item rpnexpr=>'x 25 % 15 * y 35 % 10 * getp1 !pat y 360 / !rat x y getp1 1 @rat - pmult @pat @rat pmult padd'
-
-tiles the input image over itself so that at the top of the image the
-full-size image is at full strength and at the bottom the tiling is
-most visible.
-
-=item rpnexpr=>'x y getp1 !pix @pix value 0.96 gt @pix sat 0.1 lt and 128 128 255 rgb @pix ifp'
-
-replace pixels that are white or almost white with a palish blue
-
-=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'
-
-Tiles the input image overitself where the image isn't white or almost
-white.
-
-=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'
-
-Produces a spiral.
-
-=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'
-
-A spiral built on top of a colour wheel.
-
-=back
-
-For details on expression parsing see L<Imager::Expr>. For details on
-the virtual machine used to transform the images, see
-L<Imager::regmach.pod>.
-
-=head2 Plugins
-
-It is possible to add filters to the module without recompiling the
-module itself. This is done by using DSOs (Dynamic shared object)
-avaliable on most systems. This way you can maintain our own filters
-and not have to get me to add it, or worse patch every new version of
-the Module. Modules can be loaded AND UNLOADED at runtime. This
-means that you can have a server/daemon thingy that can do something
-like:
-
- load_plugin("dynfilt/dyntest.so") || die "unable to load plugin\n";
- %hsh=(a=>35,b=>200,type=>lin_stretch);
- $img->filter(%hsh);
- unload_plugin("dynfilt/dyntest.so") || die "unable to load plugin\n";
- $img->write(type=>'pnm',file=>'testout/t60.jpg')
- || die "error in write()\n";
-
-Someone decides that the filter is not working as it should -
-dyntest.c modified and recompiled.
-
- load_plugin("dynfilt/dyntest.so") || die "unable to load plugin\n";
- $img->filter(%hsh);
-
-An example plugin comes with the module - Please send feedback to
-addi@umich.edu if you test this.
-
-Note: This seems to test ok on the following systems:
-Linux, Solaris, HPUX, OpenBSD, FreeBSD, TRU64/OSF1, AIX.
-If you test this on other systems please let me know.
-
-=head1 BUGS
-
-box, arc, circle do not support antialiasing yet. arc, is only filled
-as of yet. Some routines do not return $self where they should. This
-affects code like this, C<$img-E<gt>box()-E<gt>arc()> where an object
-is expected.
-
-When saving Gif images the program does NOT try to shave of extra
-colors if it is possible. If you specify 128 colors and there are
-only 2 colors used - it will have a 128 colortable anyway.
-
-=head1 AUTHOR
-
-Arnar M. Hrafnkelsson, addi@umich.edu
-And a great deal of help from others - see the README for a complete
-list.
-=head1 SEE ALSO
-
-perl(1), Imager::Color(3), Affix::Infix2Postfix(3), Parse::RecDescent(3)
-http://www.eecs.umich.edu/~addi/perl/Imager/
-
-
-=cut