-
Notifications
You must be signed in to change notification settings - Fork 4
/
EJCropper.php
88 lines (83 loc) · 2.16 KB
/
EJCropper.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
<?php
/**
* Base class.
*/
class EJCropper
{
/**
* @var integer JPEG image quality
*/
public $jpeg_quality = 100;
/**
* @var integer PNG compression level (0 = no compression).
*/
public $png_compression = 5;
/**
* @var integer The thumbnail width
*/
public $targ_w = 100;
/**
* @var integer The thumbnail height
*/
public $targ_h = 100;
/**
* @var string The path for saving thumbnails
*/
public $thumbPath;
/**
* Get the cropping coordinates from post.
*
* @param type $attribute The model attribute name used.
* @return array Cropping coordinates indexed by : x, y, h, w
*/
public function getCoordsFromPost($attribute)
{
$coords = array('x' => null, 'y' => null, 'h' => null, 'w' => null);
foreach ($coords as $key => $value) {
$coords[$key] = $_POST[$attribute . '_' . $key];
}
return $coords;
}
/**
* Crop an image and save the thumbnail.
*
* @param string $src Source image's full path.
* @param array $coords Cropping coordinates indexed by : x, y, h, w
* @return string $thumbName Path of thumbnail.
*/
public function crop($src, array $coords)
{
if (!$this->thumbPath) {
throw new CException(__CLASS__ . ' : thumbpath is not specified.');
}
$file_type = strtolower(pathinfo($src, PATHINFO_EXTENSION));
$thumbName = $this->thumbPath . '/' . pathinfo($src, PATHINFO_BASENAME);
if ($file_type == 'jpg' || $file_type == 'jpeg') {
$img = imagecreatefromjpeg($src);
}
elseif ($file_type == 'png') {
$img = imagecreatefrompng($src);
}
elseif ($file_type == 'gif') {
$img = imagecreatefromgif($src);
}
else {
return false;
}
$dest_r = imagecreatetruecolor($this->targ_w, $this->targ_h);
if (!imagecopyresampled($dest_r, $img, 0, 0, $coords['x'], $coords['y'], $this->targ_w, $this->targ_h, $coords['w'], $coords['h'])) {
return false;
}
// save only png or jpeg pictures
if ($file_type == 'jpg' || $file_type == 'jpeg') {
imagejpeg($dest_r, $thumbName, $this->jpeg_quality);
}
elseif ($file_type == 'png') {
imagepng($dest_r, $thumbName, $this->png_compression);
}
elseif ($file_type == 'gif') {
imagegif($dest_r, $thumbName);
}
return $thumbName;
}
}