Completed
Branch master (b0b8e5)
by samayo
01:39
created

func.image-crop.php ➔ crop()   B

Complexity

Conditions 8
Paths 13

Size

Total Lines 55
Code Lines 37

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 8
eloc 37
nc 13
nop 6
dl 0
loc 55
rs 7.4033
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * Image Croping Function. 
4
 *
5
 * @author     Daniel, Simon <[email protected]>
6
 * @link       https://github.com/samayo/bulletproof
7
 * @copyright  Copyright (c) 2015 Simon Daniel
8
 * @license    http://www.opensource.org/licenses/mit-license.html  MIT License
9
 */
10
namespace Bulletproof;
11
12
 function crop($image, $mimeType, $imgWidth, $imgHeight, $newWidth, $newHeight){
13
14
    switch ($mimeType) {
15
        case "jpg":
16
        case "jpeg":
17
            $imageCreate = imagecreatefromjpeg($image);
18
            break;
19
20
        case "png":
21
            $imageCreate = imagecreatefrompng($image);
22
            break;
23
24
        case "gif":
25
            $imageCreate = imagecreatefromgif($image);
26
            break;
27
28
        default:
29
            throw new \Exception(" Only gif, jpg, jpeg and png files can be cropped ");
30
            break;
31
    }
32
33
    // The image offsets/coordination to crop the image.
34
    $widthTrim = ceil(($imgWidth - $newWidth) / 2);
35
    $heightTrim = ceil(($imgHeight - $newHeight) / 2);
36
37
    // Can't crop to a bigger size, ex: 
38
    // an image with 100X100 can not be cropped to 200X200. Image can only be cropped to smaller size.
39
    if ($widthTrim < 0 && $heightTrim < 0) {
40
        return ;
41
    }
42
43
    $temp = imagecreatetruecolor($newWidth, $newHeight);
44
    imageAlphaBlending($temp, false);
45
    imageSaveAlpha($temp, true);
46
    imagecopyresampled(
47
        $temp,
48
        $imageCreate,
49
        0,
50
        0,
51
        $widthTrim,
52
        $heightTrim,
53
        $newWidth,
54
        $newHeight,
55
        $newWidth,
56
        $newHeight
57
    );
58
59
60
    if (!$temp) {
61
        throw new \Exception("Failed to crop image. Please pass the right parameters");
62
    } else {
63
        imagejpeg($temp, $image);
64
    }
65
66
}
67
68