1 <?php
2 /**
3 * @author Gasper Kozak
4 * @copyright 2007-2011
5
6 This file is part of WideImage.
7
8 WideImage is free software; you can redistribute it and/or modify
9 it under the terms of the GNU Lesser General Public License as published by
10 the Free Software Foundation; either version 2.1 of the License, or
11 (at your option) any later version.
12
13 WideImage is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU Lesser General Public License for more details.
17
18 You should have received a copy of the GNU Lesser General Public License
19 along with WideImage; if not, write to the Free Software
20 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
21
22 * @package Internal/Operations
23 **/
24
25 /**
26 * Crop operation class
27 *
28 * @package Internal/Operations
29 */
30 class WideImage_Operation_Crop
31 {
32 /**
33 * Returns a cropped image
34 *
35 * @param WideImage_Image $img
36 * @param smart_coordinate $left
37 * @param smart_coordinate $top
38 * @param smart_coordinate $width
39 * @param smart_coordinate $height
40 * @return WideImage_Image
41 */
42 function execute($img, $left, $top, $width, $height)
43 {
44 $width = WideImage_Coordinate::fix($width, $img->getWidth(), $width);
45 $height = WideImage_Coordinate::fix($height, $img->getHeight(), $height);
46 $left = WideImage_Coordinate::fix($left, $img->getWidth(), $width);
47 $top = WideImage_Coordinate::fix($top, $img->getHeight(), $height);
48 if ($left < 0)
49 {
50 $width = $left + $width;
51 $left = 0;
52 }
53
54 if ($width > $img->getWidth() - $left)
55 $width = $img->getWidth() - $left;
56
57 if ($top < 0)
58 {
59 $height = $top + $height;
60 $top = 0;
61 }
62
63 if ($height > $img->getHeight() - $top)
64 $height = $img->getHeight() - $top;
65
66 if ($width <= 0 || $height <= 0)
67 throw new WideImage_Exception("Can't crop outside of an image.");
68
69 $new = $img->doCreate($width, $height);
70
71 if ($img->isTransparent() || $img instanceof WideImage_PaletteImage)
72 {
73 $new->copyTransparencyFrom($img);
74 if (!imagecopyresized($new->getHandle(), $img->getHandle(), 0, 0, $left, $top, $width, $height, $width, $height))
75 throw new WideImage_GDFunctionResultException("imagecopyresized() returned false");
76 }
77 else
78 {
79 $new->alphaBlending(false);
80 $new->saveAlpha(true);
81 if (!imagecopyresampled($new->getHandle(), $img->getHandle(), 0, 0, $left, $top, $width, $height, $width, $height))
82 throw new WideImage_GDFunctionResultException("imagecopyresampled() returned false");
83 }
84 return $new;
85 }
86 }
87