-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSquareImage.php
91 lines (73 loc) · 1.76 KB
/
SquareImage.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
89
90
91
<?php
/**
*
*/
class SquareImage {
var $image;
var $thumbnailW = 70;
var $thumbnailH = 70;
function __construct($path = '') {
if (strlen($path)) {
$this->setImage($path);
}
}
function setImage($path) {
$this->image = new Imagick();
$this->image->readImageFile($path);
}
function getImage() {
return $this->$image;
}
function setThumbnailSize($w, $h) {
$this->setThumbnailWidth($w);
$this->setThumbnailHeight($h);
}
function setThumbnailWidth($w) {
$this->thumbnailW = $w;
}
function setThumbnailHeight($h) {
$this->thumbnailH = $h;
}
function getThumbnailWidth() {
return $this->thumbnailW;
}
function getThumbnailHeight() {
return $this->thumbnailH;
}
function imageEntropy($img) {
$hist = $img->getImageHistogram();
$hist_size = array_sum($hist);
$newHist = array();
foreach ($hist as $h) {
$newHist[] = float($h) / $hist_size;
}
$returnVal = 0;
foreach ($hist as $p) {
if ($p > 0) {
$returnVal += $p * log($p, 2);
}
}
return -1 * $returnVal;
}
function getSquareImage() {
$imageGeometry = $this->image->getImageGeometry();
$x = $imageGeometry['width'];
$y = $imageGeometry['height'];
while ($y > $x) {
$slice_height = min(y-x, 10);
$bottom = clone $this->image;
$top = clone $this->image;
$bottom = $bottom->cropImage(0, $y - $slice_height, $x, $y);
$top = $top->cropImage(0, 0, $x, $slice_height);
if ($this->imageEntropy($bottom) < $this->imageEntropy($top)) {
$this->image = $this->image->cropImage(0, 0, $x, $y - $slice_height);
} else {
$this->image = $this->image->crop(0, $slice_height, $x, $y);
}
$imageGeometry = $this->image->getImageGeometry();
$x = $imageGeometry['width'];
$y = $imageGeometry['height'];
}
return $this->image;
}
}