-
Notifications
You must be signed in to change notification settings - Fork 0
/
SmartImageTool.php
executable file
·495 lines (407 loc) · 18.3 KB
/
SmartImageTool.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
<?php
/**
* FR : Classe détectant automatiquement la zone la plus intéressante dans une image par exemple pour la cropper.
* Elle utilise pour cela la variation de couleur entre chaque pixel.
*
* EN : This class automatically find the most interesting zone in a picture in order to crop it.
* It uses the color variations between each pixel.
*
* @author Xavier Langlois aka XL714 <xavier.langlois@gmail.com>
* @version Release: 1.0
* @link http://todo
* @see NetOther, Net_Sample::Net_Sample()
* @since Class available since Release 1.2.0
*/
class SmartImageTool
{
public $saveDir;
public $originalImage;
public $originalImagePath;
public $originalImageRatio;
public $originalImageFileInfos;
public $originalImageWidth;
public $originalImageHeight;
public $tmpImage;
public $tmpImagePath;
public $tmpImageWidth = 40;
public $tmpImageHeight;
public $tmpImageRatio;
public $tmpImageSuffix = '_SmartImageToolTmpImage';
public $tmpImageContourMatrix = array();
public $tmpImageVariationsMatrix = array();
public $tmpImagevariationsCentroid;
public $useFilterGrayScale = true;
public $useFilterContrast = true;
public $filterContrast = -200;
public $finalImage;
public $finalImagePath;
public $finalImageRatio = 1; // e.g portrait = 0.66, landscape = 1.5, square = 1
public $finalImageWidth;
public $finalImageHeight;
public $heaviestZoneStartX = false; // as %
public $heaviestZoneStartY = false; // as %
public $errors = array();
public $flagColor;
/**
* @parameter $source: image file path or http post image array (png or jpg)
*/
public static function instance($source = false){
return new self($source);
}
public function __construct($source){
$extension = false;
if(is_array($source) && !empty($source['tmp_name']) && !empty($source['type'])){
$this->originalImagePath = $source['tmp_name'];
$extensionByType = array('image/jpeg'=>'jpg', 'image/png'=> 'png');
if(isset($extensionByType[$source['type']])){
$extension = $extensionByType[$source['type']];
}else{
$this->errors[] = 'Error: Http posted image must be a jpeg or png to use this class.';
return $this;
}
}
elseif(is_resource($source) && get_resource_type($source) == 'gd'){
$this->originalImage = $source;
}
elseif(file_exists($source)){
$this->originalImagePath = $source;
$this->originalImageFileInfos = pathinfo($this->originalImagePath); //d($fInfos); exit();
$extension = strtolower($this->originalImageFileInfos['extension']);
if( !in_array($extension, array('jpeg','jpg', 'png')) ){
$this->errors[] = 'Error: Image must be a jpeg or png to use this class.';
return $this;
}
}else{
$this->errors[] = 'Error: Invalide source. Source must be either an image filepath or an http posted image file.';
return $this;
}
if($extension) $this->originalImage = ($extension == 'png') ? imagecreatefrompng($this->originalImagePath) : ImageCreateFromJpeg($this->originalImagePath);
//$originalImageSize = getimagesize($this->originalImagePath); //d($this->originalImageSize, 'originalImageSize'); //exit();
$this->originalImageWidth = imagesx($this->originalImage); //$originalImageSize[0];
$this->originalImageHeight = imagesy($this->originalImage); //$originalImageSize[1];
$this->originalImageRatio = $this->originalImageWidth / $this->originalImageHeight; //d($this->originalImageRatio, 'originalImageRatio');
return $this;
}
public function getTmpImageSrcAsBlob(){
if(!empty($this->errors)){ return false; }
if(empty($this->tmpImage)){
$this->buildTmpImage();
}
if(!empty($this->errors)){ return false; }
return self::getImageSrcAsBlob($this->tmpImage);
}
public function getFinalImageSrcAsBlob(){
if(!empty($this->errors)){ return false; }
if(empty($this->finalImage)){
$this->buildFinalImage();
}
if(!empty($this->errors)){ return false; }
return self::getImageSrcAsBlob($this->finalImage);
}
public function getOriginalImageSrcAsBlob(){
return self::getImageSrcAsBlob($this->originalImage);
}
public static function getImageSrcAsBlob($gdImage){
ob_start();
imagepng($gdImage);
$imageBlob = ob_get_contents(); // read from buffer
ob_end_clean(); // delete buffer
return 'data:image/png;base64,'.base64_encode($imageBlob).'';
}
public function buildFinalImage(){
if(!empty($this->errors)){ return $this; }
if(empty($this->heaviestZoneStartX) && empty($this->heaviestZoneStartY)){
$this->findVariationsHeaviestZone();
}
$startX = 0;
$startY = 0;
if($this->heaviestZoneStartX !== false)
{
$this->finalImageHeight = $this->originalImageHeight;
$this->finalImageWidth = $this->finalImageHeight * $this->finalImageRatio;
$startX = round($this->heaviestZoneStartX * $this->originalImageWidth / $this->tmpImageWidth );
}
elseif($this->heaviestZoneStartY !== false)
{
$this->finalImageWidth = $this->originalImageWidth;
$this->finalImageHeight = $this->finalImageWidth / $this->finalImageRatio;
$startY = round( $this->heaviestZoneStartY * $this->originalImageHeight / $this->tmpImageHeight );
}
else{
$this->errors[] = 'Error : No heaviest zone found.';
return $this;
}
$this->finalImage = imagecreatetruecolor($this->finalImageWidth, $this->finalImageHeight);
imagecopy(
$this->finalImage, //resource $dst_im - the image object ,
$this->originalImage, // resource $src_im - destination image ,
0, // x coordinate in the destination image (use 0) ,
0, // y coordinate in the destination image (use 0) ,
$startX, // x coordinate in the source image you want to crop ,
$startY, // y coordinate in the source image you want to crop ,
$this->finalImageWidth, // crop width ,
$this->finalImageHeight // crop height
);
return $this;
}
public function findVariationsHeaviestZone(){
if(!empty($this->errors)){ return $this; }
$matrix = $this->getTmpImageVariationsMatrix();
if(!$this->originalImageRatio > $this->finalImageRatio){
$this->errors[] = 'Error : not concerned';
return $this;
}
if( $this->finalImageRatio < $this->originalImageRatio ){
$width = $this->tmpImageHeight * $this->finalImageRatio; //d($finalImageWidth, '$finalImageWidth');
$height = $this->tmpImageHeight; //d($finalImageHeight, '$finalImageHeight');
$weightByX = array();
foreach ($matrix[0] as $x => $row) {
$xMax = $x + $width;
if( $xMax >= $this->tmpImageWidth) break;
$weightByX[$x] = 0;
for($subY=0; $subY < $height; $subY++){
for($subX=$x; $subX < $xMax; $subX++){
$weightByX[$x] += $matrix[$subY][$subX];
}
}
}
arsort($weightByX); //d($weightByX, '$weightByX');
reset($weightByX);
$this->heaviestZoneStartX = key($weightByX);
}
else{
$width = $this->tmpImageWidth;
$height = $this->tmpImageWidth * $this->finalImageRatio;
$weightByY = array();
foreach($matrix as $y => $row) {
$yMax = $y + $height;
if( $yMax >= $this->tmpImageHeight) break;
$weightByY[$y] = 0;
for($subY=$y; $subY < $yMax; $subY++) {
for($subX=1; $subX < $this->tmpImageWidth; $subX++){
$weightByY[$y] += $matrix[$subY][$subX];
}
}
}
arsort($weightByY); //d($weightByY, '$weightByY');
reset($weightByY);
$this->heaviestZoneStartY = key($weightByY);
}
return $this;
}
public function showVariationsHeaviestZoneOnTmpCopy(){
if(!empty($this->errors)){ return $this; }
if(!empty($this->heaviestZoneStartX))
imagerectangle(
$this->tmpImage,
$this->heaviestZoneStartX, // X : coordonnée du coin en haut, à gauche.
0, // Y : coordonnée du coin en haut, à gauche.
($this->heaviestZoneStartX + ($this->tmpImageHeight * $this->finalImageRatio) ), // X : coordonnée du point en bas, à droite.
($this->tmpImageHeight - 1), // Y : coordonnée du point en bas, à droite.
$this->flagColor
);
return $this;
}
public function saveVariationsHeaviestZonePortraitCropped($suffix = '_cropped'){
$this->finalImagePath = $this->saveDir.'/'.$this->originalImageFileInfos['filename'].$suffix.'.png';
if(is_file($this->finalImagePath)){
unlink($this->finalImagePath);
}
ImagePng($this->finalImage, $this->finalImagePath);
chmod($this->finalImagePath, 0777);
return $this;
}
public function buildTmpImage(){
if(!empty($this->errors)){ return $this; }
$this->tmpImageRatio = ($this->tmpImageWidth * 100) / $this->originalImageWidth; //d($this->tmpImageRatio, 'ratio');
$this->tmpImageHeight = floor( ($this->originalImageHeight * $this->tmpImageRatio)/100 );
$this->tmpImage = imagecreatetruecolor($this->tmpImageWidth, $this->tmpImageHeight);
if(!$this->tmpImage){
$this->errors[] = 'Error : buildTmpImage > imagecreatetruecolor for '.$this->filepath;
return;
}
imagecopyresampled($this->tmpImage, $this->originalImage, 0, 0, 0, 0, $this->tmpImageWidth, $this->tmpImageHeight, $this->originalImageWidth, $this->originalImageHeight);
if($this->useFilterGrayScale) imagefilter($this->tmpImage, IMG_FILTER_GRAYSCALE);
if($this->useFilterContrast) imagefilter($this->tmpImage, IMG_FILTER_CONTRAST, $this->filterContrast);
$this->flagColor = imagecolorallocate($this->tmpImage, 255, 0, 0);
return $this;
}
public function saveTmpImage(){
//$this->tmpImagePath = $this->originalImageFileInfos['dirname'].'/'.$this->originalImageFileInfos['filename'].'_'.$this->tmpCopySuffix.'.png';
if(!empty($this->errors)){ return $this; }
//header ("Content-type: image/png");ImagePng ($image);exit();
if(is_file($this->tmpImagePath)){
unlink($this->tmpImagePath);
}
ImagePng($this->tmpImage, $this->tmpImagePath);
chmod($this->tmpImagePath, 0777);
return $this;
}
public function resetTmpImage(){
$this->tmpImageContourMatrix = array();
$this->tmpImageVariationsMatrix = array();
}
public function getTmpImageVariationsMatrix(){
if(!empty($this->errors)){ return $this; }
if(!empty($this->tmpImageVariationsMatrix)){
return $this->tmpImageVariationsMatrix;
}
if(empty($this->tmpImage)){
$this->buildTmpImage();
}
$this->tmpImageContourMatrix = array();
for ($y=0; $y < $this->tmpImageHeight; $y++) {
$previousRgb = false;
$reviousColors = array();
$lastWhiteX = 0;
for ($x=0; $x < $this->tmpImageWidth; $x++) {
if(!isset($lastWhiteY[$x])){
$lastWhiteY[$x] = 0;
}
$rgb = imagecolorat($this->tmpImage, $x, $y);
$colors = imagecolorsforindex($this->tmpImage, $rgb); //d($colors);exit;
//$this->tmpImageMatrix[$y][$x] = $colors;
$pixelColorsVariation = ($x) ? self::getPixelColorsVariation($colors, $previousColors) : 0;
if($pixelColorsVariation < 250) $pixelColorsVariation = 0;
$this->tmpImageVariationsMatrix[$y][$x] = $pixelColorsVariation;
// build contour matrix
if( $pixelColorsVariation == 0 )
{
if($this->tmpImageVariationsMatrix[$y][$x-1] != 0)
{
$halfColoredInterval = ($x - 1 - $lastWhiteX ) / 2;
$halfColoredIntervalX = floor( $x - $halfColoredInterval );
$this->tmpImageContourMatrix[$y][$halfColoredIntervalX] = 1;
}
$lastWhiteX = $x;
if($this->tmpImageVariationsMatrix[$y-1][$x] != 0)
{
$halfColoredInterval = ($y - 1 - $lastWhiteY[$x] ) / 2;
$halfColoredIntervalY = floor( $y - $halfColoredInterval );
$this->tmpImageContourMatrix[$halfColoredIntervalY][$x] = 1;
}
$lastWhiteY[$x] = $y;
}
$this->tmpImageContourMatrix[$y][$x] = 0;
// clean lost dot
$previousRgb =$rgb;
$previousColors = $colors;
}
}
return $this->tmpImageVariationsMatrix;
}
public static function getPixelColorsVariation($colors, $previousColors){
$variations = array();
foreach ($colors as $name => $value) {
if($previousColors[$name] != $value){
$variations[$name] = ($previousColors[$name] > $value) ? $previousColors[$name] - $value : $value - $previousColors[$name];
}else{
$variations[$name] = 0;
}
}
return array_sum($variations);
}
public function getVariationsMatrixHtml(){
$matrix = $this->getTmpImageVariationsMatrix();
$cellSize = 5;
$str = '<pre style="width:'.( count($matrix[0]) * $cellSize + 20).'px;text-align:center;">';
foreach ($matrix as $y => $row) {
if(empty($row)) break;
$str .= '<div style="margin:0;padding:0;">';
foreach($row as $x => $value) {
$c = 255 - 765 * $value / 255 ;
$str .= '<div style="display:inline-block;width:'.$cellSize.'px;height:'.$cellSize.'px;background-color:rgb('.$c.','.$c.','.$c.')"></div>';
}
$str .= '</div>';
}
$str .= '</pre>';
return $str;
//return self::matrixToHtml($matrix);
}
public static function matrixToHtml($matrix, $sprintfSize = 4){
if(empty($matrix)) return '';
$str = '<pre style="font-size:8px;line-height:10px;overflow:scroll;">';
foreach ($matrix as $y => $row) {
if(empty($row)) break;
$str .= '<div>';
foreach($row as $x => $value) {
$str .= '<span>'.sprintf("%".$sprintfSize."s", $value).'</span>';
}
$str .= '</div>';
}
$str .= '</pre>';
return $str;
}
public function getContourMatrixHtml(){
if(empty($this->tmpImageContourMatrix)) return '';
$cellSize = 5;
$str = '<pre style="width:'.( count($this->tmpImageContourMatrix[0]) * $cellSize + 20).'px;text-align:center;">';
foreach ($this->tmpImageContourMatrix as $y => $row) {
if(empty($row)) break;
$str .= '<div style="margin:0;padding:0;">';
foreach($row as $x => $value) {
$color = ($value > 0) ? 'Black' : 'White' ;
$str .= '<div style="display:inline-block;width:'.$cellSize.'px;height:'.$cellSize.'px;background-color:'.$color.'"></div>';
}
$str .= '</div>';
}
$str .= '</pre>';
return $str;
}
public function cleanExit(){
if(!empty($this->originalImage)) imagedestroy($this->originalImage);
if(!empty($this->tmpImage)) imagedestroy($this->tmpImage);
return $this;
}
// GET SET
public function getFinalImageRatio(){
return $this->finalImageRatio;
}
public function setFinalImageRatio($finalImageRatio){
if(!empty($this->finalImage)){ // zoom case
return self::instance($this->finalImage)->setFinalImageRatio($finalImageRatio);
}
$this->finalImageRatio = $finalImageRatio;
return $this;
}
public function getTmpImageWidth(){
return $this->tmpImageWidth;
}
public function setTmpImageWidth($tmpImageWidth){
$this->tmpImageWidth = $tmpImageWidth;
return $this;
}
public function getFilterContrast(){
return $this->filterContrast;
}
public function setFilterContrast($filterContrast){
$this->filterContrast = $filterContrast;
return $this;
}
// maybe useful later ?
public function findVariationsCentroid(){
if(!empty($this->errors)){ return $this; }
$matrix = $this->getTmpImageVariationsMatrix();
$this->tmpImageVariationsCentroid = self::getMatrixCentroid($matrix);
return $this;
}
public function showVariationsCentroidOnTmpCopy(){
if(!empty($this->errors)){ return $this; }
imagefilledellipse($this->tmpImage, $this->tmpImageVariationsCentroid['x'], $this->tmpImageVariationsCentroid['y'], 2, 2, $this->flagColor);
imagearc($this->tmpImage, $this->tmpImageVariationsCentroid['x'], $this->tmpImageVariationsCentroid['y'], 8, 8, 0, 360, $this->flagColor);
return $this;
}
public static function getMatrixCentroid($matrix){
$totalMass = 0;
$totalX = 0;
$totalY = 0;
foreach ($matrix as $y => $row) {
foreach ($row as $x => $value) {
$totalMass += $value;
$totalX += $x * $value;
$totalY += $y * $value;
}
}
return array('x' => $totalX/$totalMass, 'y' => $totalY/$totalMass);
}
}