3 Imager::Transformations - Simple transformations of one image into another.
9 $newimg = $img->copy();
11 $newimg = $img->scale(xpixels=>400, qtype => 'mixing');
12 $newimg = $img->scale(xpixels=>400, ypixels=>400);
13 $newimg = $img->scale(xpixels=>400, ypixels=>400, type=>'min');
14 $newimg = $img->scale(scalefactor=>0.25);
16 $newimg = $img->scaleX(pixels=>400);
17 $newimg = $img->scaleX(scalefactor=>0.25);
18 $newimg = $img->scaleY(pixels=>400);
19 $newimg = $img->scaleY(scalefactor=>0.25);
21 $newimg = $img->crop(left=>50, right=>100, top=>10, bottom=>100);
22 $newimg = $img->crop(left=>50, top=>10, width=>50, height=>90);
24 $dest->paste(left=>40,top=>20,img=>$logo);
26 $img->rubthrough(src=>$srcimage,tx=>30, ty=>50);
27 $img->rubthrough(src=>$srcimage,tx=>30, ty=>50,
28 src_minx=>20, src_miny=>30,
29 src_maxx=>20, src_maxy=>30);
31 $img->compose(src => $src, tx => 30, ty => 20, combine => 'color');
32 $img->compose(src => $src, tx => 30, ty => 20, combine => 'color');
33 mask => $mask, opacity => 0.5);
35 $img->flip(dir=>"h"); # horizontal flip
36 $img->flip(dir=>"vh"); # vertical and horizontal flip
37 $newimg = $img->copy->flip(dir=>"v"); # make a copy and flip it vertically
39 my $rot20 = $img->rotate(degrees=>20);
40 my $rotpi4 = $img->rotate(radians=>3.14159265/4);
43 # Convert image to gray
44 $new = $img->convert(preset=>'grey');
46 # Swap red/green channel
47 $new = $img->convert(matrix=>[ [ 0, 1, 0 ],
51 # limit the range of red channel from 0..255 to 0..127
52 @map = map { int( $_/2 } 0..255;
53 $img->map( red=>\@map );
55 # Apply a Gamma of 1.4
57 my @map = map { int( 0.5 + 255*($_/255)**$gamma ) } 0..255;
58 $img->map(all=>\@map); # inplace conversion
62 The methods described in Imager::Transformations fall into two categories.
63 Either they take an existing image and modify it in place, or they
64 return a modified copy.
66 Functions that modify inplace are C<flip()>, C<paste()>,
67 C<rubthrough()> and C<compose()>. If the original is to be left
68 intact it's possible to make a copy and alter the copy:
70 $flipped = $img->copy()->flip(dir=>'h');
72 =head2 Image copying/resizing/cropping/rotating
74 A list of the transformations that do not alter the source image follows:
80 To create a copy of an image use the C<copy()> method. This is useful
81 if you want to keep an original after doing something that changes the image.
83 $newimg = $orig->copy();
87 X<scale>To scale an image so proportions are maintained use the
88 C<$img-E<gt>scale()> method. if you give either a C<xpixels> or
89 C<ypixels> parameter they will determine the width or height
90 respectively. If both are given the one resulting in a larger image
91 is used, unless you set the C<type> parameter to C<'min'>. example:
92 C<$img> is 700 pixels wide and 500 pixels tall.
94 $newimg = $img->scale(xpixels=>400); # 400x285
95 $newimg = $img->scale(ypixels=>400); # 560x400
97 $newimg = $img->scale(xpixels=>400,ypixels=>400); # 560x400
98 $newimg = $img->scale(xpixels=>400,ypixels=>400,type=>'min'); # 400x285
100 $newimg = $img->scale(xpixels=>400, ypixels=>400),type=>'nonprop'); # 400x400
102 $newimg = $img->scale(scalefactor=>0.25); 175x125
103 $newimg = $img->scale(); # 350x250
105 If you want to create low quality previews of images you can pass
106 C<qtype=E<gt>'preview'> to scale and it will use nearest neighbor
107 sampling instead of filtering. It is much faster but also generates
108 worse looking images - especially if the original has a lot of sharp
109 variations and the scaled image is by more than 3-5 times smaller than
116 C<xpixels>, C<ypixels> - desired size of the scaled image. The
117 C<type> parameter controls whether the larger or smaller of the two
118 possible sizes is chosen, or if the image is scaled
123 C<constrain> - an Image::Math::Constrain object defining the way in
124 which the image size should be constrained.
128 C<scalefactor> - if none of C<xpixels>, C<ypixels>, C<xscalefactor>,
129 C<yscalefactor> or C<constrain> is supplied then this is used as the
130 ratio to scale by. Default: 0.5.
134 C<xscalefactor>, C<yscalefactor> - if both are supplied then the image is
135 scaled as per these parameters, whether this is proportionally or not.
140 C<type> - controls whether the larger or smaller of the two possible
141 sizes is chosen, possible values are:
147 C<min> - the smaller of the 2 sizes are chosen.
151 C<max> - the larger of the 2 sizes. This is the default.
155 C<nonprop> - non-proportional scaling. New in Imager 0.54.
159 scale() will fail if C<type> is set to some other value.
161 For example, if the original image is 400 pixels wide by 200 pixels
162 high and C<xpixels> is set to 300, and C<ypixels> is set to 160. When
163 C<type> is C<'min'> the resulting image is 300 x 150, when C<type> is
164 C<'max'> the resulting image is 320 x 150.
166 C<type> is only used if both C<xpixels> and C<ypixels> are supplied.
170 C<qtype> - defines the quality of scaling performed. Possible values are:
176 C<normal> - high quality scaling. This is the default.
180 C<preview> - lower quality. When scaling down this will skip input
181 pixels, eg. scaling by 0.5 will skip every other pixel. When scaling
182 up this will duplicate pixels.
186 C<mixing> - implements the mixing algorithm implemented by
187 F<pnmscale>. This retains more detail when scaling down than
188 C<normal>. When scaling down this proportionally accumulates sample
189 data from the pixels, resulting in a proportional mix of all of the
190 pixels. When scaling up this will mix pixels when the sampling grid
191 crosses a pixel boundary but will otherwise copy pixel values.
195 scale() will fail if C<qtype> is set to some other value.
197 C<preview> is faster than C<mixing> which is much faster than C<normal>.
201 To scale an image on a given axis without maintaining proportions, it
202 is best to call the scaleX() and scaleY() methods with the required
205 my $scaled = $img->scaleX(pixels=>400)->scaleY(pixels=>200);
207 From Imager 0.54 you can scale without maintaining proportions either
208 by supplying both the C<xscalefactor> and C<yscalefactor> arguments:
210 my $scaled = $img->scale(xscalefactor => 0.5, yscalefactor => 0.67);
212 or by supplying C<xpixels> and C<ypixels> and setting C<type> to
215 my $scaled = $im->scale(xpixels => 200, ypixels => 200, type => 'nonprop');
217 Returns a new scaled image on success. The source image is not
220 Returns false on failure, check the errstr() method for the reason for
223 A mandatory warning is produced if scale() is called in void context.
226 my $image = Imager->new;
227 $image->read(file => 'somefile.jpg')
228 or die $image->errstr;
230 # all full quality unless indicated otherwise
232 my $half = $image->scale;
235 my $double = $image->scale(scalefactor => 2.0);
237 # so a 400 x 400 box fits in the resulting image:
238 my $fit400x400inside = $image->scale(xpixels => 400, ypixels => 400);
239 my $fit400x400inside2 = $image->scale(xpixels => 400, ypixels => 400,
242 # fit inside a 400 x 400 box
243 my $inside400x400 = $image->scale(xpixels => 400, ypixels => 400,
246 # make it 400 pixels wide or high
247 my $width400 = $image->scale(xpixels => 400);
248 my $height400 = $image->scale(ypixels => 400);
250 # low quality scales:
252 my $low = $image->scale(qtype => 'preview');
254 # mixing method scale
255 my $mixed = $image->scale(qtype => 'mixing', scalefactor => 0.1);
257 # using an Image::Math::Constrain object
258 use Image::Math::Constrain;
259 my $constrain = Image::Math::Constrain->new(800, 600);
260 my $scaled = $image->scale(constrain => $constrain);
262 # same as Image::Math::Constrain version
263 my $scaled2 = $image->scale(xpixels => 800, ypixels => 600, type => 'min');
267 scaleX() will scale along the X dimension, return a new image with the
270 my $newimg = $img->scaleX(pixels=>400); # 400x500
271 $newimg = $img->scaleX(scalefactor=>0.25) # 175x500
277 C<scalefactor> - the amount to scale the X axis. Ignored if C<pixels> is
278 provided. Default: 0.5.
282 C<pixels> - the new width of the image.
286 Returns a new scaled image on success. The source image is not
289 Returns false on failure, check the errstr() method for the reason for
292 A mandatory warning is produced if scaleX() is called in void context.
296 scaleY() will scale along the Y dimension, return a new image with the
299 $newimg = $img->scaleY(pixels=>400); # 700x400
300 $newimg = $img->scaleY(scalefactor=>0.25) # 700x125
306 C<scalefactor> - the amount to scale the Y axis. Ignored if C<pixels> is
307 provided. Default: 0.5.
311 C<pixels> - the new height of the image.
315 Returns a new scaled image on success. The source image is not
318 Returns false on failure, check the errstr() method for the reason for
321 A mandatory warning is produced if scaleY() is called in void context.
323 =item scale_calculate()
325 Performs the same calculations that the scale() method does to
326 calculate the scaling factors from the parameters you pass.
328 scale_calculate() can be called as an object method, or as a class
331 Takes the following parameters over scale():
337 C<width>, C<height> - the image width and height to base the scaling on.
338 Required if scale_calculate() is called as a class method. If called
339 as an object method these default to the image width and height
344 You might use scale_calculate() as a class method when generating an
345 HTML C<IMG> tag, for example.
347 Returns an empty list on failure.
349 Returns a list containing horizontal scale factor, vertical scale
350 factor, new width, new height, on success.
352 my ($x_scale, $y_scale, $new_width, $new_height) =
353 Imager->scale_calculate(width => 1024, height => 768,
354 ypixels => 180, type => 'min');
356 my ($x_scale, $y_scale, $new_width, $new_height) =
357 $img->scale_calculate(xpixels => 200, type => 'min');
361 =for stopwords resize
363 Another way to resize an image is to crop it. The parameters to
364 crop are the edges of the area that you want in the returned image,
365 where the right and bottom edges are non-inclusive. If a parameter is
366 omitted a default is used instead.
368 crop() returns the cropped image and does not modify the source image.
370 The possible parameters are:
376 C<left> - the left edge of the area to be cropped. Default: 0
380 C<top> - the top edge of the area to be cropped. Default: 0
384 C<right> - the right edge of the area to be cropped. Default: right
389 C<bottom> - the bottom edge of the area to be cropped. Default:
390 bottom edge of image.
394 C<width> - width of the crop area. Ignored if both C<left> and C<right> are
395 supplied. Centered on the image if neither C<left> nor C<right> are
400 C<height> - height of the crop area. Ignored if both C<top> and
401 C<bottom> are supplied. Centered on the image if neither C<top> nor
402 C<bottom> are supplied.
408 # these produce the same image
409 $newimg = $img->crop(left=>50, right=>100, top=>10, bottom=>100);
410 $newimg = $img->crop(left=>50, top=>10, width=>50, height=>90);
411 $newimg = $img->crop(right=>100, bottom=>100, width=>50, height=>90);
413 # and the following produce the same image
414 $newimg = $img->crop(left=>50, right=>100);
415 $newimg = $img->crop(left=>50, right=>100, top=>0,
416 bottom=>$img->getheight);
418 # grab the top left corner of the image
419 $newimg = $img->crop(right=>50, bottom=>50);
421 You can also specify width and height parameters which will produce a
422 new image cropped from the center of the input image, with the given
425 $newimg = $img->crop(width=>50, height=>50);
427 If you supply C<left>, C<width> and C<right> values, the C<right>
428 value will be ignored. If you supply C<top>, C<height> and C<bottom>
429 values, the C<bottom> value will be ignored.
431 The edges of the cropped area default to the edges of the source
434 # a vertical bar from the middle from top to bottom
435 $newimg = $img->crop(width=>50);
438 $newimg = $img->crop(left=>$img->getwidth() / 2);
440 If the resulting image would have zero width or height then crop()
441 returns false and $img->errstr is an appropriate error message.
443 A mandatory warning is produced if crop() is called in void context.
447 Use the rotate() method to rotate an image. This method will return a
450 To rotate by an exact amount in degrees or radians, use the 'degrees'
451 or 'radians' parameter:
453 my $rot20 = $img->rotate(degrees=>20);
454 my $rotpi4 = $img->rotate(radians=>3.14159265/4);
456 Exact image rotation uses the same underlying transformation engine as
457 the matrix_transform() method (see Imager::Engines).
459 You can also supply a C<back> argument which acts as a background
460 color for the areas of the image with no samples available (outside
461 the rectangle of the source image.) This can be either an
462 Imager::Color or Imager::Color::Float object. This is B<not> mixed
463 transparent pixels in the middle of the source image, it is B<only>
464 used for pixels where there is no corresponding pixel in the source
467 To rotate in steps of 90 degrees, use the 'right' parameter:
469 my $rotated = $img->rotate(right=>270);
471 Rotations are clockwise for positive values.
479 C<right> - rotate by an exact multiple of 90 degrees, specified in
484 C<radians> - rotate by an angle specified in radians.
488 C<degrees> - rotate by an angle specified in degrees.
492 C<back> - for C<radians> and C<degrees> this is the color used for the
493 areas not covered by the original image. For example, the corners of
494 an image rotated by 45 degrees.
496 This can be either an Imager::Color object, an Imager::Color::Float
497 object or any parameter that Imager can convert to a color object, see
498 L<Imager::Draw/Color Parameters> for details.
500 This is B<not> mixed transparent pixels in the middle of the source
501 image, it is B<only> used for pixels where there is no corresponding
502 pixel in the source image.
504 Default: transparent black.
508 # rotate 45 degrees clockwise,
509 my $rotated = $img->rotate(degrees => 45);
511 # rotate 10 degrees counter-clockwise
512 # set pixels not sourced from the original to red
513 my $rotated = $img->rotate(degrees => -10, back => 'red');
517 =head2 Image pasting/flipping
519 A list of the transformations that alter the source image follows:
525 X<paste>To copy an image to onto another image use the C<paste()>
528 $dest->paste(left=>40, top=>20, src=>$logo);
530 That copies the entire C<$logo> image onto the C<$dest> image so that the
531 upper left corner of the C<$logo> image is at (40,20).
539 C<src>, C<img> - the source image. C<src> added for compatibility with
544 C<left>, C<top> - position in output of the top left of the pasted image.
549 C<src_minx>, C<src_miny> - the top left corner in the source image to start
550 the paste from. Default: (0, 0)
554 C<src_maxx>, C<src_maxy> - the bottom right in the source image of the sub
555 image to paste. This position is B<non> inclusive. Default: bottom
556 right corner of the source image.
560 C<width>, C<height> - if the corresponding src_maxx or src_maxy is not
561 defined then width or height is used for the width or height of the
562 sub image to be pasted.
566 # copy the 20x20 pixel image from (20,20) in $src_image to (10,10) in $img
567 $img->paste(src=>$src_image,
568 left => 10, top => 10,
569 src_minx => 20, src_miny => 20,
570 src_maxx => 40, src_maxx => 40);
572 If the source image has an alpha channel and the target doesn't, then
573 the source is treated as if composed onto a black background.
575 If the source image is color and the target is gray scale, the the
576 source is treated as if run through C<< convert(preset=>'gray') >>.
580 A more complicated way of blending images is where one image is
581 put 'over' the other with a certain amount of opaqueness. The
582 method that does this is rubthrough().
584 $img->rubthrough(src=>$overlay,
586 src_minx=>20, src_miny=>30,
587 src_maxx=>20, src_maxy=>30);
589 That will take the sub image defined by I<$overlay> and
590 I<[src_minx,src_maxx)[src_miny,src_maxy)> and overlay it on top of
591 I<$img> with the upper left corner at (30,50). You can rub 2 or 4
592 channel images onto a 3 channel image, or a 2 channel image onto a 1
593 channel image. The last channel is used as an alpha channel. To add
594 an alpha channel to an image see I<convert()>.
602 C<tx>, C<ty> - location in the the target image ($self) to render the
603 top left corner of the source.
607 C<src_minx>, C<src_miny> - the top left corner in the source to transfer to
608 the target image. Default: (0, 0).
612 C<src_maxx>, C<src_maxy> - the bottom right in the source image of the sub
613 image to overlay. This position is B<non> inclusive. Default: bottom
614 right corner of the source image.
618 # overlay all of $source onto $targ
619 $targ->rubthrough(tx => 20, ty => 25, src => $source);
621 # overlay the top left corner of $source onto $targ
622 $targ->rubthrough(tx => 20, ty => 25, src => $source,
623 src_maxx => 20, src_maxy => 20);
625 # overlay the bottom right corner of $source onto $targ
626 $targ->rubthrough(tx => 20, ty => 30, src => $src,
627 src_minx => $src->getwidth() - 20,
628 src_miny => $src->getheight() - 20);
630 rubthrough() returns true on success. On failure check
631 C<< $target->errstr >> for the reason for failure.
635 Draws the source image over the target image, with the source alpha
636 channel modified by the optional mask and the opacity.
638 $img->compose(src=>$overlay,
640 src_minx=>20, src_miny=>30,
641 src_maxx=>20, src_maxy=>30,
642 mask => $mask, opacity => 0.5);
644 That will take the sub image defined by I<$overlay> and
645 I<[src_minx,src_maxx)[src_miny,src_maxy)> and overlay it on top of
646 I<$img> with the upper left corner at (30,50). You can rub 2 or 4
647 channel images onto a 3 channel image, or a 2 channel image onto a 1
656 C<src> - the source image to draw onto the target. Required.
660 C<tx>, C<ty> - location in the the target image ($self) to render the top
661 left corner of the source. These can also be supplied as C<left> and
662 C<right>. Default: (0, 0).
666 C<src_minx>, C<src_miny> - the top left corner in the source to transfer to
667 the target image. Default: (0, 0).
671 C<src_maxx>, C<src_maxy> - the bottom right in the source image of the sub
672 image to overlay. This position is B<non> inclusive. Default: bottom
673 right corner of the source image.
677 C<mask> - a mask image. The first channel of this image is used to
678 modify the alpha channel of the source image. This can be used to
679 mask out portions of the source image. Where the first channel is
680 zero none of the source image will be used, where the first channel is
681 maximum the full alpha of the source image will be used, as further
682 modified by the opacity.
686 opacity - further modifies the alpha channel of the source image, in
687 the range 0.0 to 1.0. Default: 1.0.
691 combine - the method to combine the source pixels with the target.
692 See the combine option documentation in Imager::Fill. Default:
697 Calling compose() with no mask, combine set to C<normal>, opacity set
698 to C<1.0> is equivalent to calling rubthrough().
700 compose() is intended to be produce similar effects to layers in
701 interactive paint software.
703 # overlay all of $source onto $targ
704 $targ->compose(tx => 20, ty => 25, src => $source);
706 # overlay the top left corner of $source onto $targ
707 $targ->compose(tx => 20, ty => 25, src => $source,
708 src_maxx => 20, src_maxy => 20);
710 # overlay the bottom right corner of $source onto $targ
711 $targ->compose(tx => 20, ty => 30, src => $src,
712 src_minx => $src->getwidth() - 20,
713 src_miny => $src->getheight() - 20);
715 compose() returns true on success. On failure check $target->errstr
716 for the reason for failure.
720 An inplace horizontal or vertical flip is possible by calling the
721 C<flip()> method. If the original is to be preserved it's possible to
722 make a copy first. The only parameter it takes is the C<dir>
723 parameter which can take the values C<h>, C<v>, C<vh> and C<hv>.
725 $img->flip(dir=>"h"); # horizontal flip
726 $img->flip(dir=>"vh"); # vertical and horizontal flip
727 $nimg = $img->copy->flip(dir=>"v"); # make a copy and flip it vertically
729 flip() returns true on success. On failure check $img->errstr for the
734 =head2 Color transformations
740 You can use the convert method to transform the color space of an
741 image using a matrix. For ease of use some presets are provided.
743 The convert method can be used to:
749 convert an RGB or RGBA image to gray scale.
753 convert a gray scale image to RGB.
757 extract a single channel from an image.
761 set a given channel to a particular value (or from another channel)
765 The currently defined presets are:
771 C<gray>, C<grey> - converts an RGBA image into a gray scale image with
772 alpha channel, or an RGB image into a gray scale image without an
775 This weights the RGB channels at 22.2%, 70.7% and 7.1% respectively.
779 C<noalpha> - removes the alpha channel from a 2 or 4 channel image.
780 An identity for other images.
784 C<red>, C<channel0> - extracts the first channel of the image into a
789 C<green>, C<channel1> - extracts the second channel of the image into
790 a single channel image
794 C<blue>, C<channel2> - extracts the third channel of the image into a
799 C<alpha> - extracts the alpha channel of the image into a single
802 If the image has 1 or 3 channels (assumed to be gray scale or RGB) then
803 the resulting image will be all white.
809 converts a gray scale image to RGB, preserving the alpha channel if any
813 C<addalpha> - adds an alpha channel to a gray scale or RGB image.
814 Preserves an existing alpha channel for a 2 or 4 channel image.
818 For example, to convert an RGB image into a gray scale image:
820 $new = $img->convert(preset=>'grey'); # or gray
822 or to convert a gray scale image to an RGB image:
824 $new = $img->convert(preset=>'rgb');
826 The presets aren't necessary simple constants in the code, some are
827 generated based on the number of channels in the input image.
829 If you want to perform some other color transformation, you can use
830 the 'matrix' parameter.
832 For each output pixel the following matrix multiplication is done:
834 | channel[0] | | $c00, ..., $c0k | | inchannel[0] |
835 | ... | = | ... | x | ... |
836 | channel[k] | | $ck0, ..., $ckk | | inchannel[k] |
838 Where C<k = $img-E<gt>getchannels()-1>.
840 So if you want to swap the red and green channels on a 3 channel image:
842 $new = $img->convert(matrix=>[ [ 0, 1, 0 ],
846 or to convert a 3 channel image to gray scale using equal weightings:
848 $new = $img->convert(matrix=>[ [ 0.333, 0.333, 0.334 ] ])
850 Convert a 2 channel image (gray scale with alpha) to an RGBA image with
851 the gray converted to the specified RGB color:
853 # set (RGB) scaled on the grey scale portion and copy the alpha
855 my $colored = $gray->convert(matrix=>[ [ ($red/255), 0 ],
861 To convert a 3 channel image to a 4 channel image with a 50 percent
864 my $withalpha = $rgb->convert(matrix =>[ [ 1, 0, 0, 0 ],
872 =head2 Color Mappings
878 You can use the map method to map the values of each channel of an
879 image independently using a list of look-up tables. It's important to
880 realize that the modification is made inplace. The function simply
881 returns the input image again or undef on failure.
883 Each channel is mapped independently through a look-up table with 256
884 entries. The elements in the table should not be less than 0 and not
885 greater than 255. If they are out of the 0..255 range they are
886 clamped to the range. If a table does not contain 256 entries it is
889 Single channels can mapped by specifying their name and the mapping
890 table. The channel names are C<red>, C<green>, C<blue>, C<alpha>.
892 @map = map { int( $_/2 } 0..255;
893 $img->map( red=>\@map );
895 It is also possible to specify a single map that is applied to all
896 channels, alpha channel included. For example this applies a gamma
897 correction with a gamma of 1.4 to the input image.
900 @map = map { int( 0.5 + 255*($_/255)**$gamma ) } 0..255;
901 $img->map(all=> \@map);
903 The C<all> map is used as a default channel, if no other map is
904 specified for a channel then the C<all> map is used instead. If we
905 had not wanted to apply gamma to the alpha channel we would have used:
907 $img->map(all=> \@map, alpha=>[]);
909 Since C<[]> contains fewer than 256 element the gamma channel is
912 It is also possible to simply specify an array of maps that are
913 applied to the images in the RGBA order. For example to apply
914 maps to the C<red> and C<blue> channels one would use:
916 $img->map(maps=>[\@redmap, [], \@bluemap]);
922 L<Imager>, L<Imager::Engines>
926 Tony Cook <tony@imager.perl.org>, Arnar M. Hrafnkelsson