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 usefull
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 porportions are maintained use the
88 C<$img-E<gt>scale()> method. if you give either a xpixels or ypixels
89 parameter they will determine the width or height respectively. If
90 both are given the one resulting in a larger image is used, unless you
91 set the C<type> parameter to C<'min'>. example: C<$img> is 700 pixels
92 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 xpixels, ypixels - desired size of the scaled image. The C<type>
117 parameter controls whether the larger or smaller of the two possible
118 sizes is chosen, or if the image is scaled non-proportionally.
122 constrain - an Image::Math::Constrain object defining the way in which
123 the image size should be constrained.
127 scalefactor - if none of xpixels, ypixels, xscalefactor, yscalefactor
128 or constrain is supplied then this is used as the ratio to scale by.
133 xscalefactor, yscalefactor - if both are supplied then the image is
134 scaled as per these parameters, whether this is proportionally or not.
139 type - controls whether the larger or smaller of the two possible
140 sizes is chosen, possible values are:
146 min - the smaller of the 2 sizes are chosen.
150 max - the larger of the 2 sizes. This is the default.
154 nonprop - non-proportional scaling. New in Imager 0.54.
158 scale() will fail if C<type> is set to some other value.
160 For example, if the original image is 400 pixels wide by 200 pixels
161 high and C<xpixels> is set to 300, and C<ypixels> is set to 160. When
162 C<type> is C<'min'> the resulting image is 300 x 150, when C<type> is
163 C<'max'> the resulting image is 320 x 150.
165 C<type> is only used if both C<xpixels> and C<ypixels> are supplied.
169 qtype - defines the quality of scaling performed. Possible values are:
175 C<normal> - high quality scaling. This is the default.
179 C<preview> - lower quality. When scaling down this will skip input
180 pixels, eg. scaling by 0.5 will skip every other pixel. When scaling
181 up this will duplicate pixels.
185 C<mixing> - implements the mixing algorithm implemented by pnmscale.
186 This retains more detail when scaling down than C<normal>. When
187 scaling down this proportionally accumulates sample data from the
188 pixels, resulting in a proportional mix of all of the pixels. When
189 scaling up this will mix pixels when the sampling grid crosses a pixel
190 boundary but will otherwise copy pixel values.
194 scale() will fail if C<qtype> is set to some other value.
196 C<preview> is faster than C<mixing> which is much faster than C<normal>.
200 To scale an image on a given axis without maintaining proportions, it
201 is best to call the scaleX() and scaleY() methods with the required
204 my $scaled = $img->scaleX(pixels=>400)->scaleY(pixels=>200);
206 From Imager 0.54 you can scale without maintaining proportions either
207 by supplying both the xscalefactor and yscalefactor arguments:
209 my $scaled = $img->scale(xscalefactor => 0.5, yscalefactor => 0.67);
211 or by supplying C<xpixels> and C<ypixels> and setting C<type> to
214 my $scaled = $im->scale(xpixels => 200, ypixels => 200, type => 'nonprop');
216 Returns a new scaled image on success. The source image is not
219 Returns false on failure, check the errstr() method for the reason for
222 A mandatory warning is produced if scale() is called in void context.
225 my $image = Imager->new;
226 $image->read(file => 'somefile.jpg')
227 or die $image->errstr;
229 # all full quality unless indicated otherwise
231 my $half = $image->scale;
234 my $double = $image->scale(scalefactor => 2.0);
236 # so a 400 x 400 box fits in the resulting image:
237 my $fit400x400inside = $image->scale(xpixels => 400, ypixels => 400);
238 my $fit400x400inside2 = $image->scale(xpixels => 400, ypixels => 400,
241 # fit inside a 400 x 400 box
242 my $inside400x400 = $image->scale(xpixels => 400, ypixels => 400,
245 # make it 400 pixels wide or high
246 my $width400 = $image->scale(xpixels => 400);
247 my $height400 = $image->scale(ypixels => 400);
249 # low quality scales:
251 my $low = $image->scale(qtype => 'preview');
253 # mixing method scale
254 my $mixed = $image->scale(qtype => 'mixing', scalefactor => 0.1);
256 # using an Image::Math::Constrain object
257 use Image::Math::Constrain;
258 my $constrain = Image::Math::Constrain->new(800, 600);
259 my $scaled = $image->scale(constrain => $constrain);
261 # same as Image::Math::Constrain version
262 my $scaled2 = $image->scale(xpixels => 800, ypixels => 600, type => 'min');
266 scaleX() will scale along the X dimension, return a new image with the
269 my $newimg = $img->scaleX(pixels=>400); # 400x500
270 $newimg = $img->scaleX(scalefactor=>0.25) # 175x500
276 scalefactor - the amount to scale the X axis. Ignored if C<pixels> is
277 provided. Default: 0.5.
281 pixels - the new width of the image.
285 Returns a new scaled image on success. The source image is not
288 Returns false on failure, check the errstr() method for the reason for
291 A mandatory warning is produced if scaleX() is called in void context.
295 scaleY() will scale along the Y dimension, return a new image with the
298 $newimg = $img->scaleY(pixels=>400); # 700x400
299 $newimg = $img->scaleY(scalefactor=>0.25) # 700x125
305 scalefactor - the amount to scale the Y axis. Ignored if C<pixels> is
306 provided. Default: 0.5.
310 pixels - the new height of the image.
314 Returns a new scaled image on success. The source image is not
317 Returns false on failure, check the errstr() method for the reason for
320 A mandatory warning is produced if scaleY() is called in void context.
322 =item scale_calculate
324 Performs the same calculations that the scale() method does to
325 calculate the scaling factors from the parameters you pass.
327 scale_calculate() can be called as an object method, or as a class
330 Takes the following parameters over scale():
336 width, height - the image width and height to base the scaling on.
337 Required if scale_calculate() is called as a class method. If called
338 as an object method these default to the image width and height
343 You might use scale_calculate() as a class method when generating an
344 IMG tag, for example.
346 Returns an empty list on failure.
348 Returns a list containing horizontal scale factor, vertical scale
349 factor, new width, new height, on success.
351 my ($x_scale, $y_scale, $new_width, $new_height) =
352 Imager->scale_calculate(width => 1024, height => 768,
353 ypixels => 180, type => 'min');
355 my ($x_scale, $y_scale, $new_width, $new_height) =
356 $img->scale_calculate(xpixels => 200, type => 'min');
360 Another way to resize an image is to crop it. The parameters to
361 crop are the edges of the area that you want in the returned image,
362 where the right and bottom edges are non-inclusive. If a parameter is
363 omitted a default is used instead.
365 crop() returns the cropped image and does not modify the source image.
367 The possible parameters are:
373 C<left> - the left edge of the area to be cropped. Default: 0
377 C<top> - the top edge of the area to be cropped. Default: 0
381 C<right> - the right edge of the area to be cropped. Default: right
386 C<bottom> - the bottom edge of the area to be cropped. Default:
387 bottom edge of image.
391 C<width> - width of the crop area. Ignored if both C<left> and C<right> are
392 supplied. Centered on the image if neither C<left> nor C<right> are
397 C<height> - height of the crop area. Ignored if both C<top> and
398 C<bottom> are supplied. Centered on the image if neither C<top> nor
399 C<bottom> are supplied.
405 # these produce the same image
406 $newimg = $img->crop(left=>50, right=>100, top=>10, bottom=>100);
407 $newimg = $img->crop(left=>50, top=>10, width=>50, height=>90);
408 $newimg = $img->crop(right=>100, bottom=>100, width=>50, height=>90);
410 # and the following produce the same image
411 $newimg = $img->crop(left=>50, right=>100);
412 $newimg = $img->crop(left=>50, right=>100, top=>0,
413 bottom=>$img->getheight);
415 # grab the top left corner of the image
416 $newimg = $img->crop(right=>50, bottom=>50);
418 You can also specify width and height parameters which will produce a
419 new image cropped from the center of the input image, with the given
422 $newimg = $img->crop(width=>50, height=>50);
424 If you supply C<left>, C<width> and C<right> values, the C<right>
425 value will be ignored. If you supply C<top>, C<height> and C<bottom>
426 values, the C<bottom> value will be ignored.
428 The edges of the cropped area default to the edges of the source
431 # a vertical bar from the middle from top to bottom
432 $newimg = $img->crop(width=>50);
435 $newimg = $img->crop(left=>$img->getwidth() / 2);
437 If the resulting image would have zero width or height then crop()
438 returns false and $img->errstr is an appropriate error message.
440 A mandatory warning is produced if crop() is called in void context.
444 Use the rotate() method to rotate an image. This method will return a
447 To rotate by an exact amount in degrees or radians, use the 'degrees'
448 or 'radians' parameter:
450 my $rot20 = $img->rotate(degrees=>20);
451 my $rotpi4 = $img->rotate(radians=>3.14159265/4);
453 Exact image rotation uses the same underlying transformation engine as
454 the matrix_transform() method (see Imager::Engines).
456 You can also supply a C<back> argument which acts as a background
457 color for the areas of the image with no samples available (outside
458 the rectangle of the source image.) This can be either an
459 Imager::Color or Imager::Color::Float object. This is B<not> mixed
460 transparent pixels in the middle of the source image, it is B<only>
461 used for pixels where there is no corresponding pixel in the source
464 To rotate in steps of 90 degrees, use the 'right' parameter:
466 my $rotated = $img->rotate(right=>270);
468 Rotations are clockwise for positive values.
476 right - rotate by an exact multiple of 90 degrees, specified in
481 radians - rotate by an angle specified in radians.
485 degrees - rotate by an angle specified in degrees.
489 back - for C<radians> and C<degrees> this is the color used for the
490 areas not covered by the original image. For example, the corners of
491 an image rotated by 45 degrees.
493 This can be either an Imager::Color object, an Imager::Color::Float
494 object or any parameter that Imager can convert to a color object, see
495 L<Imager::Draw/Color Parameters> for details.
497 This is B<not> mixed transparent pixels in the middle of the source
498 image, it is B<only> used for pixels where there is no corresponding
499 pixel in the source image.
501 Default: transparent black.
505 # rotate 45 degrees clockwise,
506 my $rotated = $img->rotate(degrees => 45);
508 # rotate 10 degrees counter-clockwise
509 # set pixels not sourced from the original to red
510 my $rotated = $img->rotate(degrees => -10, back => 'red');
514 =head2 Image pasting/flipping
516 A list of the transformations that alter the source image follows:
522 X<paste>To copy an image to onto another image use the C<paste()>
525 $dest->paste(left=>40, top=>20, src=>$logo);
527 That copies the entire C<$logo> image onto the C<$dest> image so that the
528 upper left corner of the C<$logo> image is at (40,20).
536 src, img - the source image. I<src> added for compatibility with
541 left, top - position in output of the top left of the pasted image.
546 src_minx, src_miny - the top left corner in the source image to start
547 the paste from. Default: (0, 0)
551 src_maxx, src_maxy - the bottom right in the source image of the sub
552 image to paste. This position is B<non> inclusive. Default: bottom
553 right corner of the source image.
557 width, height - if the corresponding src_maxx or src_maxy is not
558 defined then width or height is used for the width or height of the
559 sub image to be pasted.
563 # copy the 20x20 pixel image from (20,20) in $src_image to (10,10) in $img
564 $img->paste(src=>$src_image,
565 left => 10, top => 10,
566 src_minx => 20, src_miny => 20,
567 src_maxx => 40, src_maxx => 40);
569 If the source image has an alpha channel and the target doesn't, then
570 the source is treated as if composed onto a black background.
572 If the source image is color and the target is grayscale, the the
573 source is treated as if run through C< convert(preset=>'gray') >.
577 A more complicated way of blending images is where one image is
578 put 'over' the other with a certain amount of opaqueness. The
579 method that does this is rubthrough.
581 $img->rubthrough(src=>$overlay,
583 src_minx=>20, src_miny=>30,
584 src_maxx=>20, src_maxy=>30);
586 That will take the sub image defined by I<$overlay> and
587 I<[src_minx,src_maxx)[src_miny,src_maxy)> and overlay it on top of
588 I<$img> with the upper left corner at (30,50). You can rub 2 or 4
589 channel images onto a 3 channel image, or a 2 channel image onto a 1
590 channel image. The last channel is used as an alpha channel. To add
591 an alpha channel to an image see I<convert()>.
599 tx, ty - location in the the target image ($self) to render the top
600 left corner of the source.
604 src_minx, src_miny - the top left corner in the source to transfer to
605 the target image. Default: (0, 0).
609 src_maxx, src_maxy - the bottom right in the source image of the sub
610 image to overlay. This position is B<non> inclusive. Default: bottom
611 right corner of the source image.
615 # overlay all of $source onto $targ
616 $targ->rubthrough(tx => 20, ty => 25, src => $source);
618 # overlay the top left corner of $source onto $targ
619 $targ->rubthrough(tx => 20, ty => 25, src => $source,
620 src_maxx => 20, src_maxy => 20);
622 # overlay the bottom right corner of $source onto $targ
623 $targ->rubthrough(tx => 20, ty => 30, src => $src,
624 src_minx => $src->getwidth() - 20,
625 src_miny => $src->getheight() - 20);
627 rubthrough() returns true on success. On failure check
628 $target->errstr for the reason for failure.
632 Draws the source image over the target image, with the src alpha
633 channel modified by the optional mask and the opacity.
635 $img->compose(src=>$overlay,
637 src_minx=>20, src_miny=>30,
638 src_maxx=>20, src_maxy=>30,
639 mask => $mask, opacity => 0.5);
641 That will take the sub image defined by I<$overlay> and
642 I<[src_minx,src_maxx)[src_miny,src_maxy)> and overlay it on top of
643 I<$img> with the upper left corner at (30,50). You can rub 2 or 4
644 channel images onto a 3 channel image, or a 2 channel image onto a 1
653 src - the source image to draw onto the target. Required.
657 tx, ty - location in the the target image ($self) to render the top
658 left corner of the source. These can also be supplied as C<left> and
659 C<right>. Default: (0, 0).
663 src_minx, src_miny - the top left corner in the source to transfer to
664 the target image. Default: (0, 0).
668 src_maxx, src_maxy - the bottom right in the source image of the sub
669 image to overlay. This position is B<non> inclusive. Default: bottom
670 right corner of the source image.
674 mask - a mask image. The first channel of this image is used to
675 modify the alpha channel of the source image. This can me used to
676 mask out portions of the source image. Where the first channel is
677 zero none of the source image will be used, where the first channel is
678 max the full alpha of the source image will be used, as further
679 modified by the opacity.
683 opacity - further modifies the alpha channel of the source image, in
684 the range 0.0 to 1.0. Default: 1.0.
688 combine - the method to combine the source pixels with the target.
689 See the combine option documentation in Imager::Fill. Default:
694 Calling compose() with no mask, combine set to C<normal>, opacity set
695 to C<1.0> is equivalent to calling rubthrough().
697 compose() is intended to be produce similar effects to layers in
698 interactive paint software.
700 # overlay all of $source onto $targ
701 $targ->compose(tx => 20, ty => 25, src => $source);
703 # overlay the top left corner of $source onto $targ
704 $targ->compose(tx => 20, ty => 25, src => $source,
705 src_maxx => 20, src_maxy => 20);
707 # overlay the bottom right corner of $source onto $targ
708 $targ->compose(tx => 20, ty => 30, src => $src,
709 src_minx => $src->getwidth() - 20,
710 src_miny => $src->getheight() - 20);
712 compose() returns true on success. On failure check $target->errstr
713 for the reason for failure.
717 An inplace horizontal or vertical flip is possible by calling the
718 C<flip()> method. If the original is to be preserved it's possible to
719 make a copy first. The only parameter it takes is the C<dir>
720 parameter which can take the values C<h>, C<v>, C<vh> and C<hv>.
722 $img->flip(dir=>"h"); # horizontal flip
723 $img->flip(dir=>"vh"); # vertical and horizontal flip
724 $nimg = $img->copy->flip(dir=>"v"); # make a copy and flip it vertically
726 flip() returns true on success. On failure check $img->errstr for the
731 =head2 Color transformations
737 You can use the convert method to transform the color space of an
738 image using a matrix. For ease of use some presets are provided.
740 The convert method can be used to:
746 convert an RGB or RGBA image to grayscale.
750 convert a grayscale image to RGB.
754 extract a single channel from an image.
758 set a given channel to a particular value (or from another channel)
762 The currently defined presets are:
770 converts an RGBA image into a grayscale image with alpha channel, or
771 an RGB image into a grayscale image without an alpha channel.
773 This weights the RGB channels at 22.2%, 70.7% and 7.1% respectively.
777 removes the alpha channel from a 2 or 4 channel image. An identity
784 extracts the first channel of the image into a single channel image
790 extracts the second channel of the image into a single channel image
796 extracts the third channel of the image into a single channel image
800 extracts the alpha channel of the image into a single channel image.
802 If the image has 1 or 3 channels (assumed to be grayscale of RGB) then
803 the resulting image will be all white.
807 converts a grayscale image to RGB, preserving the alpha channel if any
811 adds an alpha channel to a grayscale or RGB image. Preserves an
812 existing alpha channel for a 2 or 4 channel image.
816 For example, to convert an RGB image into a greyscale image:
818 $new = $img->convert(preset=>'grey'); # or gray
820 or to convert a grayscale image to an RGB image:
822 $new = $img->convert(preset=>'rgb');
824 The presets aren't necessary simple constants in the code, some are
825 generated based on the number of channels in the input image.
827 If you want to perform some other colour transformation, you can use
828 the 'matrix' parameter.
830 For each output pixel the following matrix multiplication is done:
832 | channel[0] | | $c00, ..., $c0k | | inchannel[0] |
833 | ... | = | ... | x | ... |
834 | channel[k] | | $ck0, ..., $ckk | | inchannel[k] |
836 Where C<k = $img-E<gt>getchannels()-1>.
838 So if you want to swap the red and green channels on a 3 channel image:
840 $new = $img->convert(matrix=>[ [ 0, 1, 0 ],
844 or to convert a 3 channel image to greyscale using equal weightings:
846 $new = $img->convert(matrix=>[ [ 0.333, 0.333, 0.334 ] ])
848 Convert a 2 channel image (grayscale with alpha) to an RGBA image with
849 the grey converted to the specified RGB color:
851 # set (RGB) scaled on the grey scale portion and copy the alpha
853 my $colored = $gray->convert(matrix=>[ [ ($red/255), 0 ],
859 To convert a 3 channel image to a 4 channel image with a 50 percent
862 my $withalpha = $rgb->convert(matrix =>[ [ 1, 0, 0, 0 ],
870 =head2 Color Mappings
876 You can use the map method to map the values of each channel of an
877 image independently using a list of lookup tables. It's important to
878 realize that the modification is made inplace. The function simply
879 returns the input image again or undef on failure.
881 Each channel is mapped independently through a lookup table with 256
882 entries. The elements in the table should not be less than 0 and not
883 greater than 255. If they are out of the 0..255 range they are
884 clamped to the range. If a table does not contain 256 entries it is
887 Single channels can mapped by specifying their name and the mapping
888 table. The channel names are C<red>, C<green>, C<blue>, C<alpha>.
890 @map = map { int( $_/2 } 0..255;
891 $img->map( red=>\@map );
893 It is also possible to specify a single map that is applied to all
894 channels, alpha channel included. For example this applies a gamma
895 correction with a gamma of 1.4 to the input image.
898 @map = map { int( 0.5 + 255*($_/255)**$gamma ) } 0..255;
899 $img->map(all=> \@map);
901 The C<all> map is used as a default channel, if no other map is
902 specified for a channel then the C<all> map is used instead. If we
903 had not wanted to apply gamma to the alpha channel we would have used:
905 $img->map(all=> \@map, alpha=>[]);
907 Since C<[]> contains fewer than 256 element the gamma channel is
910 It is also possible to simply specify an array of maps that are
911 applied to the images in the rgba order. For example to apply
912 maps to the C<red> and C<blue> channels one would use:
914 $img->map(maps=>[\@redmap, [], \@bluemap]);
920 L<Imager>, L<Imager::Engines>
924 Tony Cook <tony@imager.perl.org>, Arnar M. Hrafnkelsson