Image crop in php
1 /**
2 * Image crop in php
3 *
4 * @author Tomo Krajina www.panoye.com
5 */
6 function crop( $left1, $top1, $left2, $top2, $source, $dest ) {
7 $size = @getimagesize( $source );
8 if( ! $size ) {
9 return false;
10 }
11 list( $h, $w ) = $size;
12
13 if( $left1 >= $w || $left2 >= $w || $top1 >= $h || $top2 >= $h ) {
14 return false;
15 }
16
17 $img = imagecreatefromjpeg( $source );
18 $dimg = imagecreatetruecolor( $left2 - $left1, $top2 - $top1 );
19
20 imagecopyresampled( $dimg, $img,
21 0, 0, // Po?etak prvog
22 $left1, $top1, // Po?etak drugog
23 $left2 - $left1, $top2 - $top1, // kraj prvog
24 $left2, $top2 );
25
26 imagejpeg( $dimg, $dest, 100 );
27 return true;
28 }
crop an image or fit it to to size you want. It's based on imag center.
1 def fit_crop(file_path, max_width=None, max_height=None, save_as=None):
2 # Open file
3 img = Image.open(file_path)
4
5 # Store original image width and height
6 w, h = float(img.size[0]), float(img.size[1])
7
8 # Use the original size if no size given
9 max_width = float(max_width or w)
10 max_height = float(max_height or h)
11
12 # Find the closest bigger proportion to the maximum size
13 scale = max(max_width / w, max_height / h)
14
15 # Image bigger than maximum size?
16 if (scale < 1):
17 # Calculate proportions and resize
18 w = int(w * scale)
19 h = int(h * scale)
20 img = img.resize((w, h), Image.ANTIALIAS)
21 #
22
23 # Avoid enlarging the image
24 max_width = min(max_width, w)
25 max_height = min(max_height, h)
26
27 # Define the cropping box
28 left = int((w - max_width) / 2)
29 top = int((h - max_height) / 2)
30 right = int(left + max_width)
31 bottom = int(top + max_height)
32
33 # Crop to fit the desired size
34 img = img.crop( (left, top, right, bottom) )
35
36 # Save in (optional) 'save_as' or in the original path
37 img.save(save_as or file_path)
38
39 return True
Pages : 1