3 Imager::ImageTypes - image models for Imager
9 $img = Imager->new(); # Empty image (size is 0 by 0)
10 $img->open(file=>'lena.png',type=>'png'); # Read image from file
12 $img = Imager->new(xsize=>400, ysize=>300); # RGB data
14 $img = Imager->new(xsize=>400, ysize=>300, # Grayscale
17 $img = Imager->new(xsize=>400, ysize=>300, # RGB with alpha
20 $img = Imager->new(xsize=>200, ysize=>200,
21 type=>'paletted'); # paletted image
23 $img = Imager->new(xsize=>200, ysize=>200,
24 bits=>16); # 16 bits/channel rgb
26 $img = Imager->new(xsize=>200, ysize=>200,
27 bits=>'double'); # 'double' floating point
30 $img->img_set(xsize=>500, ysize=>500, # reset the image object
34 # Example getting information about an Imager object
36 print "Image information:\n";
37 print "Width: ", $img->getwidth(), "\n";
38 print "Height: ", $img->getheight(), "\n";
39 print "Channels: ", $img->getchannels(), "\n";
40 print "Bits/Channel: ", $img->bits(), "\n";
41 print "Virtual: ", $img->virtual() ? "Yes" : "No", "\n";
42 my $colorcount = $img->getcolorcount(maxcolors=>512);
43 print "Actual number of colors in image: ";
44 print defined($colorcount) ? $colorcount : ">512", "\n";
45 print "Type: ", $img->type(), "\n";
47 if ($img->type() eq 'direct') {
48 print "Modifiable Channels: ";
50 ($img->getmask() & 1<<$_) ? $_ : ()
51 } 0..$img->getchannels();
56 my $count = $img->colorcount;
57 @colors = $img->getcolors();
58 print "Palette size: $count\n";
59 my $mx = @colors > 4 ? 4 : 0+@colors;
60 print "First $mx entries:\n";
61 for (@colors[0..$mx-1]) {
63 print "(", join(", ", @res[0..$img->getchannels()-1]), ")\n";
67 my @tags = $img->tags();
71 print shift @$_, ": ", join " ", @$_, "\n";
74 print "No tags in image\n";
79 Imager supports two basic models of image:
85 direct color - all samples are stored for every pixel. eg. for an
86 8-bit/sample RGB image, 24 bits are stored for each pixel.
90 paletted - an index into a table of colors is stored for each pixel.
94 Direct color or paletted images can have 1 to 4 samples per color
95 stored. Imager treats these as follows:
101 1 sample per color - grayscale image.
105 2 samples per color - grayscale image with alpha channel.
109 3 samples per color - RGB image.
113 4 samples per color - RGB image with alpha channel.
117 Direct color images can have sample sizes of 8-bits per sample,
118 16-bits per sample or a double precision floating point number per
119 sample (64-bits on many systems).
121 Paletted images are always 8-bits/sample.
123 To query an existing image about it's parameters see the C<bits()>,
124 C<type()>, C<getwidth()>, C<getheight()>, C<getchannels()> and
125 C<virtual()> methods.
127 The coordinate system in Imager has the origin in the upper left
128 corner, see L<Imager::Draw> for details.
130 The alpha channel when one is present is considered unassociated -
131 ie. the color data has not been scaled by the alpha channel. Note
132 that not all code follows this (recent) rule, but will over time.
134 =head2 Creating Imager Objects
140 $img = Imager->new();
141 $img->read(file=>"alligator.ppm") or die $img->errstr;
143 Here C<new()> creates an empty image with width and height of zero.
144 It's only useful for creating an Imager object to call the read()
147 %opts = (xsize=>300, ysize=>200);
148 $img = Imager->new(%opts); # create direct mode RGBA image
149 $img = Imager->new(%opts, channels=>4); # create direct mode RGBA image
151 The parameters for new are:
157 C<xsize>, C<ysize> - Defines the width and height in pixels of the
158 image. These must be positive.
160 If not supplied then only placeholder object is created, which can be
161 supplied to the C<read()> or C<img_set()> methods.
165 C<channels> - The number of channels for the image. Default 3. Valid
166 values are from 1 to 4.
170 C<bits> - The storage type for samples in the image. Default: 8.
177 C<8> - One byte per sample. 256 discrete values.
181 C<16> - 16-bits per sample, 65536 discrete values.
185 C<double> - one C double per sample.
189 Note: you can use any Imager function on any sample size image.
191 Paletted images always use 8 bits/sample.
195 C<type> - either C<'direct'> or C<'paletted'>. Default: C<'direct'>.
197 Direct images store color values for each pixel.
199 Paletted images keep a table of up to 256 colors called the palette,
200 each pixel is represented as an index into that table.
202 In most cases when working with Imager you will want to use the
203 C<direct> image type.
205 If you draw on a C<paletted> image with a color not in the image's
206 palette then Imager will transparently convert it to a C<direct>
211 C<maxcolors> - the maximum number of colors in a paletted image.
212 Default: 256. This must be in the range 1 through 256.
216 In the simplest case just supply the width and height of the image:
218 # 8 bit/sample, RGB image
219 my $img = Imager->new(xsize => $width, ysize => $height);
221 or if you want an alpha channel:
223 # 8 bits/sample, RGBA image
224 my $img = Imager->new(xsize => $width, ysize => $height, channels=>4);
226 Note that it I<is> possible for image creation to fail, for example if
227 channels is out of range, or if the image would take too much memory.
229 To create paletted images, set the 'type' parameter to 'paletted':
231 $img = Imager->new(xsize=>200, ysize=>200, type=>'paletted');
233 which creates an image with a maxiumum of 256 colors, which you can
234 change by supplying the C<maxcolors> parameter.
236 For improved color precision you can use the bits parameter to specify
239 $img = Imager->new(xsize=>200, ysize=>200,
240 channels=>3, bits=>16);
242 or for even more precision:
244 $img = Imager->new(xsize=>200, ysize=>200,
245 channels=>3, bits=>'double');
247 to get an image that uses a double for each channel.
249 Note that as of this writing all functions should work on images with
250 more than 8-bits/channel, but many will only work at only
251 8-bit/channel precision.
253 If you want an empty Imager object to call the read() method on, just
254 call new() with no parameters:
256 my $img = Imager->new;
257 $img->read(file=>$filename)
262 img_set destroys the image data in the object and creates a new one
263 with the given dimensions and channels. For a way to convert image
264 data between formats see the C<convert()> method.
266 $img->img_set(xsize=>500, ysize=>500, channels=>4);
268 This takes exactly the same parameters as the new() method.
272 =head2 Getting Information About an Imager Object
278 print "Image width: ", $img->getwidth(), "\n";
280 The C<getwidth()> method returns the width of the image. This value
281 comes either from C<new()> with xsize,ysize parameters or from reading
282 data from a file with C<read()>. If called on an image that has no
283 valid data in it like C<Imager-E<gt>new()> returns, the return value
284 of C<getwidth()> is undef.
288 print "Image height: ", $img->getheight(), "\n";
290 Same details apply as for L<getwidth>.
294 print "Image has ",$img->getchannels(), " channels\n";
296 To get the number of channels in an image C<getchannels()> is used.
301 It is possible to have Imager find the number of colors in an image by
302 with the C<getcolorcount()> method. It requires memory proportionally
303 to the number of colors in the image so it is possible to have it stop
304 sooner if you only need to know if there are more than a certain
305 number of colors in the image. If there are more colors than asked
306 for the function return undef. Examples:
308 if (defined($img->getcolorcount(maxcolors=>512)) {
309 print "Less than 512 colors in image\n";
315 The bits() method retrieves the number of bits used to represent each
316 channel in a pixel, 8 for a normal image, 16 for 16-bit image and
317 'double' for a double/channel image.
319 if ($img->bits eq 8) {
320 # fast but limited to 8-bits/sample
323 # slower but more precise
328 The type() method returns either 'direct' for truecolor images or
329 'paletted' for paletted images.
331 if ($img->type eq 'paletted') {
333 for my $color ($img->getcolors) {
334 print join(",", $color->rgba), "\n";
340 The virtual() method returns non-zero if the image contains no actual
341 pixels, for example masked images.
343 This may also be used for non-native Imager images in the future, for
344 example, for an Imager object that draws on an SDL surface.
348 =head2 Direct Type Images
350 Direct images store the color value directly for each pixel in the
357 @rgbanames = qw( red green blue alpha );
358 my $mask = $img->getmask();
359 print "Modifiable channels:\n";
360 for (0..$img->getchannels()-1) {
361 print $rgbanames[$_],"\n" if $mask & 1<<$_;
364 C<getmask()> is used to fetch the current channel mask. The mask
365 determines what channels are currently modifiable in the image. The
366 channel mask is an integer value, if the i-th lsb is set the i-th
367 channel is modifiable. eg. a channel mask of 0x5 means only channels
368 0 and 2 are writable.
372 $mask = $img->getmask();
373 $img->setmask(mask=>8); # modify alpha only
377 $img->setmask(mask=>$mask); # restore previous mask
379 C<setmask()> is used to set the channel mask of the image. See
380 L<getmask> for details.
384 =head2 Palette Type Images
386 Paletted images keep an array of up to 256 colors, and each pixel is
387 stored as an index into that array.
389 In general you can work with paletted images in the same way as RGB
390 images, except that if you attempt to draw to a paletted image with a
391 color that is not in the image's palette, the image will be converted
392 to an RGB image. This means that drawing on a paletted image with
393 anti-aliasing enabled will almost certainly convert the image to RGB.
395 Palette management takes place through C<addcolors()>, C<setcolors()>,
396 C<getcolors()> and C<findcolor()>:
402 You can add colors to a paletted image with the addcolors() method:
404 my @colors = ( Imager::Color->new(255, 0, 0),
405 Imager::Color->new(0, 255, 0) );
406 my $index = $img->addcolors(colors=>\@colors);
408 The return value is the index of the first color added, or undef if
409 adding the colors would overflow the palette.
411 The only parameter is C<colors> which must be a reference to an array
412 of Imager::Color objects.
416 $img->setcolors(start=>$start, colors=>\@colors);
418 Once you have colors in the palette you can overwrite them with the
419 C<setcolors()> method: C<setcolors()> returns true on success.
427 start - the first index to be set. Default: 0
431 colors - reference to an array of Imager::Color objects.
437 To retrieve existing colors from the palette use the getcolors() method:
439 # get the whole palette
440 my @colors = $img->getcolors();
442 my $color = $img->getcolors(start=>$index);
443 # get a range of colors
444 my @colors = $img->getcolors(start=>$index, count=>$count);
448 To quickly find a color in the palette use findcolor():
450 my $index = $img->findcolor(color=>$color);
452 which returns undef on failure, or the index of the color.
460 color - an Imager::Color object.
466 Returns the number of colors in the image's palette:
468 my $count = $img->colorcount;
472 Returns the maximum size of the image's palette.
474 my $maxcount = $img->maxcolors;
478 =head2 Conversion Between Image Types
480 Warning: if you draw on a paletted image with colors that aren't in
481 the palette, the image will be internally converted to a normal image.
487 You can create a new paletted image from an existing image using the
488 to_paletted() method:
490 $palimg = $img->to_paletted(\%opts)
492 where %opts contains the options specified under L<Quantization options>.
494 # convert to a paletted image using the web palette
495 # use the closest color to each pixel
496 my $webimg = $img->to_paletted({ make_colors => 'webmap' });
498 # convert to a paletted image using a fairly optimal palette
499 # use an error diffusion dither to try to reduce the average error
500 my $optimag = $img->to_paletted({ make_colors => 'mediancut',
501 translate => 'errdiff' });
505 You can convert a paletted image (or any image) to an 8-bit/channel
508 $rgbimg = $img->to_rgb8;
514 You can convert a paletted image (or any image) to an 16-bit/channel
517 $rgbimg = $img->to_rgb16;
523 Creates a masked image. A masked image lets you create an image proxy
524 object that protects parts of the underlying target image.
526 In the discussion below there are 3 image objects involved:
532 the masked image - the return value of the masked() method. Any
533 writes to this image are written to the target image, assuming the
534 mask image allows it.
538 the mask image - the image that protects writes to the target image.
539 Supplied as the C<mask> parameter to the masked() method.
543 the target image - the image you called the masked() method on. Any
544 writes to the masked image end up on this image.
554 mask - the mask image. If not supplied then all pixels in the target
555 image are writable. On each write to the masked image, only pixels
556 that have non-zero in chennel 0 of the mask image will be written to
557 the original image. Default: none, if not supplied then no masking is
558 done, but the other parameters are still honored.
562 left, top - the offset of writes to the target image. eg. if you
563 attempt to set pixel (x,y) in the masked image, then pixel (x+left,
564 y+top) will be written to in the original image.
568 bottom, right - the bottom right of the area in the target available
569 from the masked image.
573 Masked images let you control which pixels are modified in an
574 underlying image. Where the first channel is completely black in the
575 mask image, writes to the underlying image are ignored.
577 For example, given a base image called $img:
579 my $mask = Imager->new(xsize=>$img->getwidth, ysize=>$img->getheight,
581 # ... draw something on the mask
582 my $maskedimg = $img->masked(mask=>$mask);
584 # now draw on $maskedimg and it will only draw on areas of $img
585 # where $mask is non-zero in channel 0.
587 You can specifiy the region of the underlying image that is masked
588 using the left, top, right and bottom options.
590 If you just want a subset of the image, without masking, just specify
591 the region without specifying a mask. For example:
593 # just work with a 100x100 region of $img
594 my $maskedimg = $img->masked(left => 100, top=>100,
595 right=>200, bottom=>200);
601 Image tags contain meta-data about the image, ie. information not
602 stored as pixels of the image.
604 At the perl level each tag has a name or code and a value, which is an
605 integer or an arbitrary string. An image can contain more than one
606 tag with the same name or code, but having more than one tag with the
607 same name is discouraged.
609 You can retrieve tags from an image using the tags() method, you can
610 get all of the tags in an image, as a list of array references, with
611 the code or name of the tag followed by the value of the tag.
617 Retrieve tags from the image.
619 With no parameters, retrieves a list array references, each containing
620 a name and value: all tags in the image:
622 # get a list of ( [ name1 => value1 ], [ name2 => value2 ] ... )
623 my @alltags = $img->tags;
624 print $_->[0], ":", $_->[1], "\n" for @all_tags;
626 # or put it in a hash, but this will lose duplicates
627 my %alltags = map @$_, $img->tags;
629 in scalar context this returns the number of tags:
631 my $num_tags = $img->tags;
633 or you can get all tags values for the given name:
635 my @namedtags = $img->tags(name => $name);
637 in scalar context this returns the first tag of that name:
639 my $firstnamed = $img->tags(name => $name);
643 my @tags = $img->tags(code=>$code);
647 You can add tags using the addtag() method, either by name:
649 my $index = $img->addtag(name=>$name, value=>$value);
653 my $index = $img->addtag(code=>$code, value=>$value);
657 You can remove tags with the deltag() method, either by index:
659 $img->deltag(index=>$index);
663 $img->deltag(name=>$name);
667 $img->deltag(code=>$code);
669 In each case deltag() returns the number of tags deleted.
673 settag() replaces any existing tags with a new tag. This is
674 equivalent to calling deltag() then addtag().
680 Many tags are only meaningful for one format. GIF looping information
681 is pretty useless for JPEG for example. Thus, many tags are set by
682 only a single reader or used by a single writer. For a complete list
683 of format specific tags see L<Imager::Files>.
685 Since tags are a relatively new addition their use is not wide spread
686 but eventually we hope to have all the readers for various formats set
687 some standard information.
693 X<i_xres tag>X<i_yres tag>X<tags, i_xres>X<tags, i_yres>i_xres, i_yres
694 - The spatial resolution of the image in pixels per inch. If the
695 image format uses a different scale, eg. pixels per meter, then this
696 value is converted. A floating point number stored as a string.
698 # our image was generated as a 300 dpi image
699 $img->settag(name => 'i_xres', value => 300);
700 $img->settag(name => 'i_yres', value => 300);
702 # 100 pixel/cm for a TIFF image
703 $img->settag(name => 'tiff_resolutionunit', value => 3); # RESUNIT_CENTIMETER
704 # convert to pixels per inch, Imager will convert it back
705 $img->settag(name => 'i_xres', value => 100 * 2.54);
706 $img->settag(name => 'i_yres', value => 100 * 2.54);
710 X<i_aspect_only tag>X<tags, i_aspect_only>i_aspect_only - If this is
711 non-zero then the values in i_xres and i_yres are treated as a ratio
712 only. If the image format does not support aspect ratios then this is
713 scaled so the smaller value is 72dpi.
717 X<i_incomplete tag>X<tags, i_incomplete>i_incomplete - If this tag is
718 present then the whole image could not be read. This isn't
719 implemented for all images yet, and may not be.
723 X<i_lines_read tag>X<tags, i_lines_read>i_lines_read - If
724 C<i_incomplete> is set then this tag may be set to the number of
725 scanlines successfully read from the file. This can be used to decide
726 whether an image is worth processing.
730 X<i_format tag>X<tags, i_format>i_format - The file format this file
735 =head2 Quantization options
737 These options can be specified when calling
738 L<Imager::ImageTypes/to_paletted>, write_multi() for gif files, when
739 writing a single image with the gifquant option set to 'gen', or for
740 direct calls to i_writegif_gen and i_writegif_callback.
746 A arrayref of colors that are fixed. Note that some color generators
751 The type of transparency processing to perform for images with an
752 alpha channel where the output format does not have a proper alpha
753 channel (eg. gif). This can be any of:
759 No transparency processing is done. (default)
763 Pixels more transparent that tr_threshold are rendered as transparent.
767 An error diffusion dither is done on the alpha channel. Note that
768 this is independent of the translation performed on the colour
769 channels, so some combinations may cause undesired artifacts.
773 The ordered dither specified by tr_orddith is performed on the alpha
778 This will only be used if the image has an alpha channel, and if there
779 is space in the palette for a transparency colour.
783 The highest alpha value at which a pixel will be made transparent when
784 transp is 'threshold'. (0-255, default 127)
788 The type of error diffusion to perform on the alpha channel when
789 transp is 'errdiff'. This can be any defined error diffusion type
790 except for custom (see errdiff below).
794 The type of ordered dither to perform on the alpha channel when transp
795 is 'ordered'. Possible values are:
801 A semi-random map is used. The map is the same each time.
813 horizontal line dither.
817 vertical line dither.
833 dot matrix dither (currently the default). This is probably the best
834 for displays (like web pages).
838 A custom dither matrix is used - see tr_map
844 When tr_orddith is custom this defines an 8 x 8 matrix of integers
845 representing the transparency threshold for pixels corresponding to
846 each position. This should be a 64 element array where the first 8
847 entries correspond to the first row of the matrix. Values should be
852 Defines how the quantization engine will build the palette(s).
853 Currently this is ignored if 'translate' is 'giflib', but that may
854 change. Possible values are:
860 none - only colors supplied in 'colors' are used.
864 webmap - the web color map is used (need url here.)
868 addi - The original code for generating the color map (Addi's code) is
873 mediancut - Uses a mediancut algorithm, faster than 'addi', but not as good a
878 mono, monochrome - a fixed black and white palette, suitable for
879 producing bi-level images (eg. facsimile)
883 Other methods may be added in the future.
887 A arrayref containing Imager::Color objects, which represents the
888 starting set of colors to use in translating the images. webmap will
889 ignore this. The final colors used are copied back into this array
890 (which is expanded if necessary.)
894 The maximum number of colors to use in the image.
898 The method used to translate the RGB values in the source image into
899 the colors selected by make_colors. Note that make_colors is ignored
900 whene translate is 'giflib'.
908 The giflib native quantization function is used.
912 The closest color available is used.
916 The pixel color is modified by perturb, and the closest color is chosen.
920 An error diffusion dither is performed.
924 It's possible other transate values will be added.
928 The type of error diffusion dither to perform. These values (except
929 for custom) can also be used in tr_errdif.
935 Floyd-Steinberg dither
939 Jarvis, Judice and Ninke dither
947 Custom. If you use this you must also set errdiff_width,
948 errdiff_height and errdiff_map.
960 When translate is 'errdiff' and errdiff is 'custom' these define a
961 custom error diffusion map. errdiff_width and errdiff_height define
962 the size of the map in the arrayref in errdiff_map. errdiff_orig is
963 an integer which indicates the current pixel position in the top row
968 When translate is 'perturb' this is the magnitude of the random bias
969 applied to each channel of the pixel before it is looked up in the
974 =head1 INITIALIZATION
976 This documents the Imager initialization function, which you will
977 almost never need to call.
983 This is a function, not a method.
985 This function is a mess, it can take the following named parameters:
991 log - name of a log file to log Imager's actions to. Not all actions
992 are logged, but the debugging memory allocator does log allocations
993 here. Ignored if Imager has been built without logging support.
997 loglevel - the maximum level of message to log. Default: 1.
1001 warn_obsolete - if this is non-zero then Imager will warn when you
1002 attempt to use obsoleted parameters or functionality. This currently
1003 only includes the old gif output options instead of tags.
1007 t1log - if non-zero then T1lib will be configured to produce a log
1008 file. This will fail if there are any existing T1lib font objects.
1014 Imager::init(log => 'trace.log', loglevel => 9);
1024 Tony Cook, Arnar M. Hrafnkelsson
1028 Imager(3), Imager::Files(3), Imager::Draw(3),
1029 Imager::Color(3), Imager::Fill(3), Imager::Font(3),
1030 Imager::Transformations(3), Imager::Engines(3), Imager::Filters(3),
1031 Imager::Expr(3), Imager::Matrix2d(3), Imager::Fountain(3)