]> git.imager.perl.org - imager.git/blob - lib/Imager/Transformations.pod
664bfdf2652accb87ef3265d4b37935692752a7e
[imager.git] / lib / Imager / Transformations.pod
1 =head1 NAME
2
3 Imager::Transformations - Simple transformations of one image into another.
4
5 =head1 SYNOPSIS
6
7   use Imager;
8
9   $newimg = $img->copy();
10
11   $newimg = $img->scale(xpixels=>400);
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);
15
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);
20
21   $newimg = $img->crop(left=>50, right=>100, top=>10, bottom=>100); 
22   $newimg = $img->crop(left=>50, top=>10, width=>50, height=>90);
23
24   $dest->paste(left=>40,top=>20,img=>$logo);
25
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);
30
31
32   $img->flip(dir=>"h");       # horizontal flip
33   $img->flip(dir=>"vh");      # vertical and horizontal flip
34   $newimg = $img->copy->flip(dir=>"v"); # make a copy and flip it vertically
35
36   my $rot20 = $img->rotate(degrees=>20);
37   my $rotpi4 = $img->rotate(radians=>3.14159265/4);
38
39
40   # Convert image to gray
41   $new = $img->convert(preset=>'grey');          
42
43   # Swap red/green channel  
44   $new = $img->convert(matrix=>[ [ 0, 1, 0 ],
45                                  [ 1, 0, 0 ],
46                                  [ 0, 0, 1 ] ]);
47
48   # limit the range of red channel from 0..255 to 0..127
49   @map = map { int( $_/2 } 0..255;
50   $img->map( red=>\@map );
51
52   # Apply a Gamma of 1.4
53   my $gamma = 1.4;
54   my @map = map { int( 0.5 + 255*($_/255)**$gamma ) } 0..255;
55   $img->map(all=>\@map);  # inplace conversion
56
57 =head1 DESCRIPTION
58
59 The methods described in Imager::Transformations fall into two categories.
60 Either they take an existing image and modify it in place, or they 
61 return a modified copy.
62
63 Functions that modify inplace are C<flip()>, C<paste()> and
64 C<rubthrough()>.  If the original is to be left intact it's possible
65 to make a copy and alter the copy:
66
67   $flipped = $img->copy()->flip(dir=>'h');
68
69 =head2 Image copying/resizing/cropping/rotating
70
71 A list of the transformations that do not alter the source image follows:
72
73 =over
74
75 =item copy
76
77 To create a copy of an image use the C<copy()> method.  This is usefull
78 if you want to keep an original after doing something that changes the image.
79
80   $newimg = $orig->copy();
81
82 =item scale
83
84 X<scale>To scale an image so porportions are maintained use the
85 C<$img-E<gt>scale()> method.  if you give either a xpixels or ypixels
86 parameter they will determine the width or height respectively.  If
87 both are given the one resulting in a larger image is used, unless you
88 set the C<type> parameter to C<'min'>.  example: C<$img> is 700 pixels
89 wide and 500 pixels tall.
90
91   $newimg = $img->scale(xpixels=>400); # 400x285
92   $newimg = $img->scale(ypixels=>400); # 560x400
93
94   $newimg = $img->scale(xpixels=>400,ypixels=>400); # 560x400
95   $newimg = $img->scale(xpixels=>400,ypixels=>400,type=>'min'); # 400x285
96
97   $newimg = $img->scale(scalefactor=>0.25); 175x125 
98   $newimg = $img->scale(); # 350x250
99
100 if you want to create low quality previews of images you can pass
101 C<qtype=E<gt>'preview'> to scale and it will use nearest neighbor
102 sampling instead of filtering. It is much faster but also generates
103 worse looking images - especially if the original has a lot of sharp
104 variations and the scaled image is by more than 3-5 times smaller than
105 the original.
106
107 =over
108
109 =item *
110
111 xpixels, ypixels - desired size of the scaled image.  The resulting
112 image is always scaled proportionally.  The C<type> parameter controls
113 whether the larger or smaller of the two possible sizes is chosen.
114
115 =item *
116
117 constrain - an Image::Math::Constrain object defining the way in which
118 the image size should be constrained.
119
120 =item *
121
122 scalefactor - if none of xpixels, ypixels or constrain is supplied
123 then this is used as the ratio to scale by.  Default: 0.5.
124
125 =item *
126
127 type - controls whether the larger or smaller of the two possible
128 sizes is chosen, possible values are:
129
130 =over
131
132 =item *
133
134 min - the smaller of the 2 sizes are chosen.
135
136 =item *
137
138 max - the larger of the 2 sizes.  This is the default.
139
140 =back
141
142 scale() will fail if C<type> is set to some other value.
143
144 For example, if the original image is 400 pixels wide by 200 pixels
145 high and C<xpixels> is set to 300, and C<ypixels> is set to 160.  When
146 C<type> is C<'min'> the resulting image is 300 x 150, when C<type> is
147 C<'max'> the resulting image is 320 x 150.
148
149 C<type> is only used if both C<xpixels> and C<ypixels> are supplied.
150
151 =item *
152
153 qtype - defines the quality of scaling performed.  Possible values are:
154
155 =over
156
157 =item *
158
159 normal - high quality scaling.  This is the default.
160
161 =item *
162
163 preview - lower quality.
164
165 =back
166
167 scale() will fail if C<qtype> is set to some other value.
168
169 =back
170
171 To scale an image on a given axis without maintaining proportions, it
172 is best to call the scaleX() and scaleY() methods with the required
173 dimensions. eg.
174
175   my $scaled = $img->scaleX(pixels=>400)->scaleY(pixels=>200);
176
177 Returns the scaled image on success.
178
179 Returns false on failure, check the errstr() method for the reason for
180 failure.
181
182 A mandatory warning is produced if scale() is called in void context.
183
184   # setup
185   my $image = Imager->new;
186   $image->read(file => 'somefile.jpg')
187     or die $image->errstr;
188
189   # all full quality unless indicated otherwise
190   # half the size:
191   my $half = $image->scale;
192
193   # double the size
194   my $double = $image->scale(scalefactor => 2.0);
195
196   # so a 400 x 400 box fits in the resulting image:
197   my $fit400x400inside = $image->scale(xpixels => 400, ypixels => 400);
198   my $fit400x400inside2 = $image->scale(xpixels => 400, ypixels => 400,
199                                         type=>'max');
200
201   # fit inside a 400 x 400 box
202   my $inside400x400 = $image->scale(xpixels => 400, ypixels => 400,
203                               type=>'min');
204
205   # make it 400 pixels wide or high
206   my $width400 = $image->scale(xpixels => 400);
207   my $height400 = $image->scale(ypixels => 400);
208
209   # low quality scales:
210   # to half size
211   my $low = $image->scale(qtype => 'preview');
212
213   # using an Image::Math::Constrain object
214   use Image::Math::Constrain;
215   my $constrain = Image::Math::Constrain->new(800, 600);
216   my $scaled = $image->scale(constrain => $constrain);
217
218   # same as Image::Math::Constrain version
219   my $scaled2 = $image->scale(xpixels => 800, ypixels => 600, type => 'min');
220
221 =item scaleX
222
223 scaleX() will scale along the X dimension, return a new image with the
224 new width:
225
226   my $newimg = $img->scaleX(pixels=>400); # 400x500
227   $newimg = $img->scaleX(scalefactor=>0.25) # 175x500
228
229 =over
230
231 =item *
232
233 scalefactor - the amount to scale the X axis.  Ignored if C<pixels> is
234 provided.  Default: 0.5.
235
236 =item *
237
238 pixels - the new width of the image.
239
240 =back
241
242 Returns the scaled image on success.
243
244 Returns false on failure, check the errstr() method for the reason for
245 failure.
246
247 A mandatory warning is produced if scaleX() is called in void context.
248
249 =item scaleY
250
251 scaleY() will scale along the Y dimension, return a new image with the
252 new height:
253
254   $newimg = $img->scaleY(pixels=>400); # 700x400
255   $newimg = $img->scaleY(scalefactor=>0.25) # 700x125
256
257 =over
258
259 =item *
260
261 scalefactor - the amount to scale the Y axis.  Ignored if C<pixels> is
262 provided.  Default: 0.5.
263
264 =item *
265
266 pixels - the new height of the image.
267
268 =back
269
270 Returns the scaled image on success.
271
272 Returns false on failure, check the errstr() method for the reason for
273 failure.
274
275 A mandatory warning is produced if scaleY() is called in void context.
276
277 =item crop
278
279 Another way to resize an image is to crop it.  The parameters to
280 crop are the edges of the area that you want in the returned image,
281 where the right and bottom edges are non-inclusive.  If a parameter is
282 omitted a default is used instead.
283
284 crop() returns the cropped image and does not modify the source image.
285
286 The possible parameters are:
287
288 =over
289
290 =item *
291
292 C<left> - the left edge of the area to be cropped.  Default: 0
293
294 =item *
295
296 C<top> - the top edge of the area to be cropped.  Default: 0
297
298 =item *
299
300 C<right> - the right edge of the area to be cropped.  Default: right
301 edge of image.
302
303 =item *
304
305 C<bottom> - the bottom edge of the area to be cropped.  Default:
306 bottom edge of image.
307
308 =item *
309
310 C<width> - width of the crop area.  Ignored if both C<left> and C<right> are
311 supplied.  Centered on the image if neither C<left> nor C<right> are
312 supplied.
313
314 =item *
315
316 C<height> - height of the crop area.  Ignored if both C<top> and
317 C<bottom> are supplied.  Centered on the image if neither C<top> nor
318 C<bottom> are supplied.
319
320 =back
321
322 For example:
323
324   # these produce the same image
325   $newimg = $img->crop(left=>50, right=>100, top=>10, bottom=>100); 
326   $newimg = $img->crop(left=>50, top=>10, width=>50, height=>90);
327   $newimg = $img->crop(right=>100, bottom=>100, width=>50, height=>90);
328
329   # and the following produce the same image
330   $newimg = $img->crop(left=>50, right=>100);
331   $newimg = $img->crop(left=>50, right=>100, top=>0, 
332                        bottom=>$img->getheight);
333
334   # grab the top left corner of the image
335   $newimg = $img->crop(right=>50, bottom=>50);
336
337 You can also specify width and height parameters which will produce a
338 new image cropped from the center of the input image, with the given
339 width and height.
340
341   $newimg = $img->crop(width=>50, height=>50);
342
343 If you supply C<left>, C<width> and C<right> values, the C<right>
344 value will be ignored.  If you supply C<top>, C<height> and C<bottom>
345 values, the C<bottom> value will be ignored.
346
347 The edges of the cropped area default to the edges of the source
348 image, for example:
349
350   # a vertical bar from the middle from top to bottom
351   $newimg = $img->crop(width=>50);
352
353   # the right half
354   $newimg = $img->crop(left=>$img->getwidth() / 2);
355
356 If the resulting image would have zero width or height then crop()
357 returns false and $img->errstr is an appropriate error message.
358
359 A mandatory warning is produced if crop() is called in void context.
360
361 =item rotate
362
363 Use the rotate() method to rotate an image.  This method will return a
364 new, rotated image.
365
366 To rotate by an exact amount in degrees or radians, use the 'degrees'
367 or 'radians' parameter:
368
369   my $rot20 = $img->rotate(degrees=>20);
370   my $rotpi4 = $img->rotate(radians=>3.14159265/4);
371
372 Exact image rotation uses the same underlying transformation engine as
373 the matrix_transform() method (see Imager::Engines).
374
375 You can also supply a C<back> argument which acts as a background
376 color for the areas of the image with no samples available (outside
377 the rectangle of the source image.)  This can be either an
378 Imager::Color or Imager::Color::Float object.  This is B<not> mixed
379 transparent pixels in the middle of the source image, it is B<only>
380 used for pixels where there is no corresponding pixel in the source
381 image.
382
383 To rotate in steps of 90 degrees, use the 'right' parameter:
384
385   my $rotated = $img->rotate(right=>270);
386
387 Rotations are clockwise for positive values.
388
389 Parameters:
390
391 =over
392
393 =item *
394
395 right - rotate by an exact multiple of 90 degrees, specified in
396 degreess.
397
398 =item *
399
400 radians - rotate by an angle specified in radians.
401
402 =item *
403
404 degrees - rotate by an angle specified in degrees.
405
406 =item *
407
408 back - for C<radians> and C<degrees> this is the color used for the
409 areas not covered by the original image.  For example, the corners of
410 an image rotated by 45 degrees.
411
412 This can be either an Imager::Color object, an Imager::Color::Float
413 object or any parameter that Imager can convert to a color object, see
414 L<Imager::Draw/Color Parameters> for details.
415
416 This is B<not> mixed transparent pixels in the middle of the source
417 image, it is B<only> used for pixels where there is no corresponding
418 pixel in the source image.
419
420 Default: transparent black.
421
422 =back
423
424   # rotate 45 degrees clockwise, 
425   my $rotated = $img->rotate(degrees => 45);
426
427   # rotate 10 degrees counter-clockwise
428   # set pixels not sourced from the original to red
429   my $rotated = $img->rotate(degrees => -10, back => 'red');
430
431 =back
432
433 =head2 Image pasting/flipping
434
435 A list of the transformations that alter the source image follows:
436
437 =over
438
439 =item paste
440
441 X<paste>To copy an image to onto another image use the C<paste()>
442 method.
443
444   $dest->paste(left=>40, top=>20, src=>$logo);
445
446 That copies the entire C<$logo> image onto the C<$dest> image so that the
447 upper left corner of the C<$logo> image is at (40,20).
448
449 Parameters:
450
451 =over
452
453 =item *
454
455 src, img - the source image.  I<src> added for compatibility with
456 rubthrough().
457
458 =item *
459
460 left, top - position in output of the top left of the pasted image.
461 Default: (0,0)
462
463 =item *
464
465 src_minx, src_miny - the top left corner in the source image to start
466 the paste from.  Default: (0, 0)
467
468 =item *
469
470 src_maxx, src_maxy - the bottom right in the source image of the sub
471 image to paste.  This position is B<non> inclusive.  Default: bottom
472 right corner of the source image.
473
474 =item *
475
476 width, height - if the corresponding src_maxx or src_maxy is not
477 defined then width or height is used for the width or height of the
478 sub image to be pasted.
479
480 =back
481
482   # copy the 20x20 pixel image from (20,20) in $src_image to (10,10) in $img
483   $img->paste(src=>$src_image,
484               left => 10, top => 10,
485               src_minx => 20, src_miny => 20,
486               src_maxx => 40, src_maxx => 40);
487               
488 =item rubthrough
489
490 A more complicated way of blending images is where one image is
491 put 'over' the other with a certain amount of opaqueness.  The
492 method that does this is rubthrough.
493
494   $img->rubthrough(src=>$overlay,
495                    tx=>30,       ty=>50,
496                    src_minx=>20, src_miny=>30,
497                    src_maxx=>20, src_maxy=>30);
498
499 That will take the sub image defined by I<$overlay> and
500 I<[src_minx,src_maxx)[src_miny,src_maxy)> and overlay it on top of
501 I<$img> with the upper left corner at (30,50).  You can rub 2 or 4
502 channel images onto a 3 channel image, or a 2 channel image onto a 1
503 channel image.  The last channel is used as an alpha channel.  To add
504 an alpha channel to an image see I<convert()>.
505
506 Parameters:
507
508 =over
509
510 =item *
511
512 tx, ty - location in the the target image ($self) to render the top
513 left corner of the source.
514
515 =item *
516
517 src_minx, src_miny - the top left corner in the source to transfer to
518 the target image.  Default: (0, 0).
519
520 =item *
521
522 src_maxx, src_maxy - the bottom right in the source image of the sub
523 image to overlay.  This position is B<non> inclusive.  Default: bottom
524 right corner of the source image.
525
526 =back
527
528   # overlay all of $source onto $targ
529   $targ->rubthrough(tx => 20, ty => 25, src => $source);
530
531   # overlay the top left corner of $source onto $targ
532   $targ->rubthrough(tx => 20, ty => 25, src => $source,
533                     src_maxx => 20, src_maxy => 20);
534
535   # overlay the bottom right corner of $source onto $targ
536   $targ->rubthrough(tx => 20, ty => 30, src => $src,
537                     src_minx => $src->getwidth() - 20,
538                     src_miny => $src->getheight() - 20);
539
540 rubthrough() returns true on success.  On failure check
541 $target->errstr for the reason for failure.
542
543 =item flip
544
545 An inplace horizontal or vertical flip is possible by calling the
546 C<flip()> method.  If the original is to be preserved it's possible to
547 make a copy first.  The only parameter it takes is the C<dir>
548 parameter which can take the values C<h>, C<v>, C<vh> and C<hv>.
549
550   $img->flip(dir=>"h");       # horizontal flip
551   $img->flip(dir=>"vh");      # vertical and horizontal flip
552   $nimg = $img->copy->flip(dir=>"v"); # make a copy and flip it vertically
553
554 flip() returns true on success.  On failure check $img->errstr for the
555 reason for failure.
556
557 =back
558
559 =head2 Color transformations
560
561 You can use the convert method to transform the color space of an
562 image using a matrix.  For ease of use some presets are provided.
563
564 The convert method can be used to:
565
566 =over
567
568 =item *
569
570 convert an RGB or RGBA image to grayscale.
571
572 =item *
573
574 convert a grayscale image to RGB.
575
576 =item *
577
578 extract a single channel from an image.
579
580 =item *
581
582 set a given channel to a particular value (or from another channel)
583
584 =back
585
586 The currently defined presets are:
587
588 =over
589
590 =item gray
591
592 =item grey
593
594 converts an RGBA image into a grayscale image with alpha channel, or
595 an RGB image into a grayscale image without an alpha channel.
596
597 This weights the RGB channels at 22.2%, 70.7% and 7.1% respectively.
598
599 =item noalpha
600
601 removes the alpha channel from a 2 or 4 channel image.  An identity
602 for other images.
603
604 =item red
605
606 =item channel0
607
608 extracts the first channel of the image into a single channel image
609
610 =item green
611
612 =item channel1
613
614 extracts the second channel of the image into a single channel image
615
616 =item blue
617
618 =item channel2
619
620 extracts the third channel of the image into a single channel image
621
622 =item alpha
623
624 extracts the alpha channel of the image into a single channel image.
625
626 If the image has 1 or 3 channels (assumed to be grayscale of RGB) then
627 the resulting image will be all white.
628
629 =item rgb
630
631 converts a grayscale image to RGB, preserving the alpha channel if any
632
633 =item addalpha
634
635 adds an alpha channel to a grayscale or RGB image.  Preserves an
636 existing alpha channel for a 2 or 4 channel image.
637
638 =back
639
640 For example, to convert an RGB image into a greyscale image:
641
642   $new = $img->convert(preset=>'grey'); # or gray
643
644 or to convert a grayscale image to an RGB image:
645
646   $new = $img->convert(preset=>'rgb');
647
648 The presets aren't necessary simple constants in the code, some are
649 generated based on the number of channels in the input image.
650
651 If you want to perform some other colour transformation, you can use
652 the 'matrix' parameter.
653
654 For each output pixel the following matrix multiplication is done:
655
656   | channel[0] |   | $c00, ...,  $c0k |   | inchannel[0] |
657   |    ...     | = |       ...        | x |     ...      |
658   | channel[k] |   | $ck0, ...,  $ckk |   | inchannel[k] |
659                                                           1
660 Where C<k = $img-E<gt>getchannels()-1>.
661
662 So if you want to swap the red and green channels on a 3 channel image:
663
664   $new = $img->convert(matrix=>[ [ 0, 1, 0 ],
665                                  [ 1, 0, 0 ],
666                                  [ 0, 0, 1 ] ]);
667
668 or to convert a 3 channel image to greyscale using equal weightings:
669
670   $new = $img->convert(matrix=>[ [ 0.333, 0.333, 0.334 ] ])
671
672 Convert a 2 channel image (grayscale with alpha) to an RGBA image with
673 the grey converted to the specified RGB color:
674
675   # set (RGB) scaled on the grey scale portion and copy the alpha
676   # channel as is
677   my $colored = $gray->convert(matrix=>[ [ ($red/255),   0 ], 
678                                          [ ($green/255), 0 ], 
679                                          [ ($blue/255),  0 ], 
680                                          [ 0,            1 ],
681                                        ]);
682
683 To convert a 3 channel image to a 4 channel image with a 50 percent
684 alpha channel:
685
686   my $withalpha = $rgb->convert(matrix =>[ [ 1, 0, 0, 0 ],
687                                            [ 0, 1, 0, 0 ],
688                                            [ 0, 0, 1, 0 ],
689                                            [ 0, 0, 0, 0.5 ],
690                                          ]);
691
692 =head2 Color Mappings
693
694 You can use the map method to map the values of each channel of an
695 image independently using a list of lookup tables.  It's important to
696 realize that the modification is made inplace.  The function simply
697 returns the input image again or undef on failure.
698
699 Each channel is mapped independently through a lookup table with 256
700 entries.  The elements in the table should not be less than 0 and not
701 greater than 255.  If they are out of the 0..255 range they are
702 clamped to the range.  If a table does not contain 256 entries it is
703 silently ignored.
704
705 Single channels can mapped by specifying their name and the mapping
706 table.  The channel names are C<red>, C<green>, C<blue>, C<alpha>.
707
708   @map = map { int( $_/2 } 0..255;
709   $img->map( red=>\@map );
710
711 It is also possible to specify a single map that is applied to all
712 channels, alpha channel included.  For example this applies a gamma
713 correction with a gamma of 1.4 to the input image.
714
715   $gamma = 1.4;
716   @map = map { int( 0.5 + 255*($_/255)**$gamma ) } 0..255;
717   $img->map(all=> \@map);
718
719 The C<all> map is used as a default channel, if no other map is
720 specified for a channel then the C<all> map is used instead.  If we
721 had not wanted to apply gamma to the alpha channel we would have used:
722
723   $img->map(all=> \@map, alpha=>[]);
724
725 Since C<[]> contains fewer than 256 element the gamma channel is
726 unaffected.
727
728 It is also possible to simply specify an array of maps that are
729 applied to the images in the rgba order.  For example to apply
730 maps to the C<red> and C<blue> channels one would use:
731
732   $img->map(maps=>[\@redmap, [], \@bluemap]);
733
734 =head1 SEE ALSO
735
736 L<Imager>, L<Imager::Engines>
737
738 =head1 AUTHOR
739
740 Tony Cook <tony@imager.perl.org>, Arnar M. Hrafnkelsson
741
742 =head1 REVISION
743
744 $Revision$
745
746 =cut