Completed
Branch master (dacad6)
by samayo
02:24 queued 01:12
created

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

Complexity

Conditions 8
Paths 13

Size

Total Lines 56
Code Lines 37

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 8
eloc 37
nc 13
nop 6
dl 0
loc 56
rs 7.3333
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
15
    switch ($mimeType) {
16
        case "jpg":
17
        case "jpeg":
18
            $imageCreate = imagecreatefromjpeg($image);
19
            break;
20
21
        case "png":
22
            $imageCreate = imagecreatefrompng($image);
23
            break;
24
25
        case "gif":
26
            $imageCreate = imagecreatefromgif($image);
27
            break;
28
29
        default:
30
            throw new \Exception(" Only gif, jpg, jpeg and png files can be cropped ");
31
            break;
32
    }
33
34
    // The image offsets/coordination to crop the image.
35
    $widthTrim = ceil(($imgWidth - $newWidth) / 2);
36
    $heightTrim = ceil(($imgHeight - $newHeight) / 2);
37
38
    // Can't crop to a bigger size, ex: 
39
    // an image with 100X100 can not be cropped to 200X200. Image can only be cropped to smaller size.
40
    if ($widthTrim < 0 && $heightTrim < 0) {
41
        return;
42
    }
43
44
    $temp = imagecreatetruecolor($newWidth, $newHeight);
45
    imageAlphaBlending($temp, false);
46
    imageSaveAlpha($temp, true);
47
    imagecopyresampled(
48
        $temp,
49
        $imageCreate,
50
        0,
51
        0,
52
        $widthTrim,
53
        $heightTrim,
54
        $newWidth,
55
        $newHeight,
56
        $newWidth,
57
        $newHeight
58
    );
59
60
61
    if (!$temp) {
62
        throw new \Exception("Failed to crop image. Please pass the right parameters");
63
    } else {
64
        imagejpeg($temp, $image);
65
    }
66
67
}
68
69