Subversion Repositories eFlore/Applications.cel

Rev

Rev 672 | Rev 1154 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
591 aurelien 1
<?php
632 aurelien 2
Class ImageRecreation {
591 aurelien 3
 
672 jpm 4
	private $droits = 0705;
632 aurelien 5
	private $formats = array('CRX2S','CXS','CS','CRS','XS','S','M','L','XL','X2L','X3L');
6
	const MODE_GD = 'gd';
7
	const MODE_IMAGEMAGICK = 'imagemagick';
8
	private $mode;
9
 
10
	private $verbose = true;
591 aurelien 11
 
672 jpm 12
	public function __construct($config) {
13
		$this->config = $config;
632 aurelien 14
		$this->mode = self::MODE_GD;
15
 
16
		if (extension_loaded('imagick')) {
970 aurelien 17
			putenv('MAGICK_TEMPORARY_PATH='.$this->config['cel']['chemin_stockage_temp']);
632 aurelien 18
			$this->mode = self::MODE_IMAGEMAGICK;
19
		}
591 aurelien 20
	}
21
 
632 aurelien 22
	public function recreerMiniaturesRecursivement() {
970 aurelien 23
		$this->itererRecursivement($this->config['cel']['chemin_images']);
632 aurelien 24
	}
25
 
26
	public function regenererMiniaturesIntervalle($params) {
27
		$id_debut = $params[0];
28
		$id_fin = $params[1];
29
 
30
		if (is_numeric($id_debut) && is_numeric($id_fin)) {
668 aurelien 31
			for ($i = $id_debut; $i <= $id_fin; $i++) {;
632 aurelien 32
			    $tab_param = array($i);
33
			    $this->regenererMiniaturesPourId($tab_param);
34
			}
35
		}
591 aurelien 36
	}
37
 
632 aurelien 38
	public function regenererMiniaturesPourId($params) {
39
		$id = $params[0];
40
 
41
		if (!is_numeric($id)) {
42
		      return;
43
		}
44
 
45
		$dossier_fichier = $this->obtenirDossierPourFormat($id, 'O');
46
		$nom_fichier = $this->convertirIdBddVersNomFichier($id, 'O');
47
 
48
		$chemin_fichier = $dossier_fichier.'/'.$nom_fichier;
49
 
50
		if(file_exists($chemin_fichier)) {
51
			$infos_image_originale = $this->obtenirImageEtInfosPourChemin($chemin_fichier);
52
 
53
			// creation de miniatures pour chacuns des formats définis
54
			foreach($this->formats as $format) {
55
				$this->creerEtStockerMiniatureFichierImageSelonFormat($id, $infos_image_originale, $format);
668 aurelien 56
			};
57
 
632 aurelien 58
		}
621 aurelien 59
	}
591 aurelien 60
 
605 aurelien 61
	public function itererRecursivement($dossier) {
591 aurelien 62
		// on ne parse que le dossier des images originales
63
		$dossiers_a_exclure = $this->getFormats();
64
 
65
		foreach (new DirectoryIterator($dossier) as $fichier_ou_dossier) {
632 aurelien 66
			if ($fichier_ou_dossier->isDot()) {
591 aurelien 67
				continue;
68
			}
69
 
632 aurelien 70
			if (in_array($fichier_ou_dossier->getBasename(), $dossiers_a_exclure)) {
591 aurelien 71
				continue;
72
			}
73
 
632 aurelien 74
		    if ($fichier_ou_dossier->isDir()) {
668 aurelien 75
	    		$this->itererRecursivement($fichier_ou_dossier->getPathname());
591 aurelien 76
		    } else {
77
		    	$nom_fichier = $fichier_ou_dossier->getFilename();
78
 
79
				$infos_image_originale = $this->obtenirImageEtInfosPourChemin($fichier_ou_dossier->getPathname());
605 aurelien 80
		    	$id = $this->convertirBaseNomFichierVersIdBdd($nom_fichier, $this->formats);
591 aurelien 81
 
82
		    	// creation de miniatures pour chacuns des formats définis
605 aurelien 83
				foreach($this->formats as $format) {
591 aurelien 84
					$this->creerEtStockerMiniatureFichierImageSelonFormat($id, $infos_image_originale, $format);
85
				}
86
		    }
87
		}
88
	}
668 aurelien 89
 
90
	public function creerMiniatureImageSelonFormat($infos_image_originale, $format = 'O') {
632 aurelien 91
		if ($format == 'O') {
591 aurelien 92
			// format original : rien à faire
93
			$image_redimensionnee = $infos_image_originale['image'];
94
 
95
		} else {
632 aurelien 96
			 if ($this->estUnFormatRogne($format)) {
97
			 	if ($this->mode == self::MODE_IMAGEMAGICK) {
98
			 		// si l'on dispose de la librairie imageMagick
99
			 		// on applique l'algorithme d'auto détection de sujets
100
			 		// qui centre la miniature sur le sujet de l'image
101
			 		$image_redimensionnee = $this->opticrop($infos_image_originale, $format);
102
			 	} else {
103
			 		// si l'on ne dispose que de gd
104
					// la minature est une image redimensionnée rognée au centre
105
					$image_redimensionnee = $this->creerMiniatureCarreeRognee($infos_image_originale, $format);
106
			 	}
107
			} else if ($this->estUnFormatCarre($format)) {
591 aurelien 108
				// le format carre et une image redimensionnée en gardant son ratio, insérée dans un carré blanc
109
				$image_redimensionnee = $this->creerMiniatureCarree($infos_image_originale, $format);
110
			} else {
111
				$image_redimensionnee = $this->creerMiniature($infos_image_originale, $format);
112
			}
113
		}
668 aurelien 114
 
115
		return $image_redimensionnee;
116
	}
117
 
118
	public function creerEtStockerMiniatureFichierImageSelonFormat($id ,$infos_image_originale, $format = 'O') {
119
		$image_redimensionnee = $this->creerMiniatureImageSelonFormat($infos_image_originale, $format);
591 aurelien 120
 
121
		$taux_compression = $this->renvoyerTauxCompressionPourPoids($infos_image_originale['poids_octets']);
122
		$this->ecrireImageSurDisque($image_redimensionnee, $id, $format, $taux_compression);
123
 
124
		return true;
125
	}
126
 
127
	public function creerImageRedimensionnee($infos_image_originale, $hauteur_redimension, $largeur_redimension) {
128
		$image_redimensionnee = imagecreatetruecolor($largeur_redimension, $hauteur_redimension);
129
 
130
		imagecopyresampled($image_redimensionnee,
672 jpm 131
			$infos_image_originale['image'],
132
			0, 0,
133
			0, 0,
134
			$largeur_redimension,
135
			$hauteur_redimension,
136
			$infos_image_originale['largeur'],
137
			$infos_image_originale['hauteur']
591 aurelien 138
		);
139
 
140
		return $image_redimensionnee;
141
	}
142
 
143
	public function creerMiniature($informations_images, $format) {
144
		$taille_reference_pour_format = $this->obtenirDimensionsPourFormat($format);
145
 
146
		$taille_image_redimensionnee = $this->calculerTailleImage($informations_images, $taille_reference_pour_format['hauteur']);
147
		$image_redimensionnee = $this->creerImageRedimensionnee($informations_images, $taille_image_redimensionnee['hauteur'], $taille_image_redimensionnee['largeur']);
148
 
149
		return $image_redimensionnee;
150
	}
151
 
152
	public function creerMiniatureCarree($informations_image, $format) {
153
		$taille_reference_pour_format = $this->obtenirDimensionsPourFormat($format);
154
		$cote_carre = $taille_reference_pour_format['largeur'];
155
 
156
		$image_redimensionnee_avec_rapport = $this->creerMiniature($informations_image, $format);
157
		$taille_redimensionnee_avec_rapport = $this->calculerTailleImage($informations_image, $taille_reference_pour_format['hauteur']);
158
 
632 aurelien 159
		if ($this->estPaysage($informations_image)) {
672 jpm 160
			$debut_largeur_a_copier = 0 ;
161
			$debut_hauteur_a_copier = ($cote_carre - $taille_redimensionnee_avec_rapport['hauteur'])/2 ;
591 aurelien 162
		} else {
672 jpm 163
			$debut_largeur_a_copier = ($cote_carre - $taille_redimensionnee_avec_rapport['largeur'])/2 ;
164
			$debut_hauteur_a_copier = 0 ;
591 aurelien 165
		}
166
 
167
		$image_carre_blanc_cible = $this->renvoyerEtCreerImageCarreeBlancheSelonFormat($cote_carre);
168
 
169
		imagecopy($image_carre_blanc_cible, $image_redimensionnee_avec_rapport,
672 jpm 170
			$debut_largeur_a_copier ,$debut_hauteur_a_copier, 0, 0,
171
			$taille_redimensionnee_avec_rapport['largeur'], $taille_redimensionnee_avec_rapport['hauteur']
591 aurelien 172
		);
173
 
174
		return $image_carre_blanc_cible;
175
	}
176
 
177
	public function creerMiniatureCarreeRognee($informations_image, $format) {
178
		$taille_reference_pour_format = $this->obtenirDimensionsPourFormat($format);
179
		$cote_carre = $taille_reference_pour_format['largeur'];
180
		$cote_carre_non_redimensionne = 0;
181
 
632 aurelien 182
		if ($this->estPaysage($informations_image)) {
672 jpm 183
			$cote_carre_non_redimensionne = $informations_image['hauteur'];
184
			$debut_largeur_a_copier = ($informations_image['hauteur'] - $cote_carre)/2 ;
185
			$debut_hauteur_a_copier = 0;
186
 
187
			if($debut_largeur_a_copier <= 0) {
188
				$debut_largeur_a_copier = 0;
189
			}
190
 
191
			$nb_pixels_largeur_a_copier = $cote_carre_non_redimensionne;
192
			$nb_pixels_hauteur_a_copier = $cote_carre_non_redimensionne;
193
		} else {
194
			$cote_carre_non_redimensionne = $informations_image['largeur'];
195
			$debut_largeur_a_copier = 0 ;
196
			$debut_hauteur_a_copier = ($informations_image['largeur'] - $cote_carre)/2;
197
 
198
			if($debut_hauteur_a_copier <= 0) {
591 aurelien 199
				$debut_hauteur_a_copier = 0;
672 jpm 200
			}
201
 
202
			$nb_pixels_largeur_a_copier = $cote_carre_non_redimensionne;
203
			$nb_pixels_hauteur_a_copier = $cote_carre_non_redimensionne;
591 aurelien 204
		}
205
 
206
		$image_carre_temporaire = imagecreatetruecolor($cote_carre_non_redimensionne, $cote_carre_non_redimensionne);
207
 
208
		imagecopyresampled($image_carre_temporaire,
672 jpm 209
			$informations_image['image'],
210
			0, 0,
211
			$debut_largeur_a_copier,
212
			$debut_hauteur_a_copier,
213
			$cote_carre_non_redimensionne,
214
			$cote_carre_non_redimensionne,
215
			$nb_pixels_largeur_a_copier,
216
			$nb_pixels_hauteur_a_copier
591 aurelien 217
		);
218
 
219
		$image_redimensionnee = imagecreatetruecolor($cote_carre, $cote_carre);
220
 
221
		imagecopyresampled($image_redimensionnee,
672 jpm 222
			$image_carre_temporaire,
223
			0, 0,
224
			0, 0,
225
			$cote_carre,
226
			$cote_carre,
227
			$cote_carre_non_redimensionne,
228
			$cote_carre_non_redimensionne
591 aurelien 229
		);
230
 
231
		return $image_redimensionnee;
232
	}
233
 
621 aurelien 234
	public function stockerFichierEtCreerMiniatures($fichier, $id) {
591 aurelien 235
		$chemin_base_fichier = $this->creerSiNecessaireEtRenvoyerCheminStockageFichierPourIdEtFormat($id, 'O');
236
		$nom_fichier = $this->convertirIdBddVersNomFichier($id, 'O');
237
 
238
		$chemin_fichier = $chemin_base_fichier.'/'.$nom_fichier;
239
 
632 aurelien 240
		$deplacement_fichier = $this->stockerImageExterne($fichier['tmp_name'], $chemin_fichier);
241
 
242
		if ($deplacement_fichier) {
591 aurelien 243
 
244
			$infos_image_originale = $this->obtenirImageEtInfosPourChemin($chemin_fichier);
245
			$taux_compression = $this->renvoyerTauxCompressionPourPoids($infos_image_originale['poids_octets']);
246
 
632 aurelien 247
			if ($taux_compression < 100 && $this->mode == self::MODE_IMAGEMAGICK) {
248
				$this->ecrireImageSurDisqueAvecMeta($chemin_fichier, $taux_compression);
591 aurelien 249
			}
250
 
251
			$infos_image_originale_stockee = $this->obtenirImageEtInfosPourChemin($chemin_fichier);
252
 
253
			$formats = $this->getFormats();
254
 
255
			// creation de miniatures pour chacuns des formats définis
256
			foreach($formats as $format) {
257
				$this->creerEtStockerMiniatureFichierImageSelonFormat($id, $infos_image_originale_stockee, $format);
258
			}
259
 
260
	  		return true ;
261
 
262
		} else {
263
			$erreur =  'ERROR : probleme durant le déplacement du fichier temporaire \n' ;
264
			$this->logger('CEL_bugs',$erreur);
265
  			return false ;
266
		}
267
	}
268
 
632 aurelien 269
	public function stockerImageExterne($chemin_fichier_temp, $chemin_destination) {
270
		if(is_uploaded_file($chemin_fichier_temp)) {
271
			$deplacement = move_uploaded_file($chemin_fichier_temp, $chemin_destination);
272
		} else {
273
			$deplacement = rename($chemin_fichier_temp, $chemin_destination);
274
		}
275
 
276
		return $deplacement;
277
	}
278
 
591 aurelien 279
	public function creerSiNecessaireEtRenvoyerCheminStockageFichierPourIdEtFormat($id, $format) {
672 jpm 280
		$chemin_sur_serveur_final = $this->obtenirDossierPourFormat($id, $format);
591 aurelien 281
 
672 jpm 282
		if (!file_exists($chemin_sur_serveur_final)) {
668 aurelien 283
			umask(0);
672 jpm 284
			if (!mkdir($chemin_sur_serveur_final, $this->droits, true)) {
591 aurelien 285
				$erreur =  'ERROR : probleme durant l\'écriture du dossier '.$format.' \n' ;
672 jpm 286
				$this->logger('CEL_bugs', $erreur);
591 aurelien 287
				return false;
288
			}
289
		}
290
 
291
		return $chemin_sur_serveur_final;
292
	}
293
 
294
	public function obtenirDossierPourFormat($id, $format) {
970 aurelien 295
		$chemin_base = $this->config['cel']['chemin_images'];
591 aurelien 296
 
672 jpm 297
		$chemin_sur_serveur = $chemin_base;
591 aurelien 298
 
672 jpm 299
		$id = sprintf('%09s', $id);
300
		$id = wordwrap($id, 3 , '_', true);
591 aurelien 301
 
672 jpm 302
		list($dossierNiveau1, $dossierNiveau2) = explode('_', $id);
591 aurelien 303
 
304
		$chemin_sur_serveur_final = $chemin_sur_serveur.'/'.$dossierNiveau1.'/'.$dossierNiveau2.'/'.$format;
305
 
306
		return $chemin_sur_serveur_final;
307
	}
308
 
668 aurelien 309
	public function obtenirCheminImageOriginale($id_image) {
310
		$nom = $this->convertirIdBddVersNomFichier($id_image, 'O');
311
		$dossier = $this->obtenirDossierPourFormat($id_image,'O');
312
 
313
		return $dossier.'/'.$nom;
314
	}
315
 
316
	public function obtenirImageEtInfosPourId($id_image) {
317
		$chemin_image_o = $this->obtenirCheminImageOriginale($id_image);
318
		return $this->obtenirImageEtInfosPourChemin($chemin_image_o);
319
	}
320
 
591 aurelien 321
	public function obtenirImageEtInfosPourChemin($chemin_fichier) {
668 aurelien 322
		$image_et_infos = false;
591 aurelien 323
 
672 jpm 324
		if (file_exists($chemin_fichier)) {
668 aurelien 325
			$image_et_infos = array();
326
			list($image_et_infos['largeur'], $image_et_infos['hauteur']) = getimagesize($chemin_fichier);
327
			$image_et_infos['poids_octets'] = filesize($chemin_fichier);
328
			$image_et_infos['image'] = imagecreatefromjpeg($chemin_fichier);
329
			$image_et_infos['chemin'] = $chemin_fichier;
330
		}
591 aurelien 331
 
332
		return $image_et_infos;
333
	}
334
 
335
	public function obtenirDimensionsPourFormat($format) {
672 jpm 336
		$dimensions = array('largeur' => 0, 'hauteur' => 0);
591 aurelien 337
 
970 aurelien 338
		if (isset($this->config['cel']['format_'.$format])) {
339
			list($dimensions['largeur'], $dimensions['hauteur']) = explode('_', $this->config['cel']['format_'.$format]);
591 aurelien 340
		}
341
 
342
		return $dimensions;
343
	}
344
 
345
	public function calculerTailleImage($informations_images, $taille_max) {
672 jpm 346
        $HL_redimension = array();
347
 
348
        if ($this->estPaysage($informations_images)) {
349
	        $rapport = $informations_images['hauteur']/$informations_images['largeur'] ;
350
	        $HL_redimension['largeur'] = round($taille_max) ;
351
	        $HL_redimension['hauteur'] = round($taille_max*$rapport) ;
591 aurelien 352
 
672 jpm 353
        } else {
354
        	$rapport = $informations_images['largeur']/$informations_images['hauteur'] ;
355
	        $HL_redimension['hauteur'] = round($taille_max) ;
356
	        $HL_redimension['largeur'] = round($taille_max*$rapport) ;
357
        }
358
 
359
        return $HL_redimension;
591 aurelien 360
	}
361
 
362
	public function getFormats() {
363
		return $this->formats;
364
	}
365
 
366
	public function estUnFormatCarre($format) {
367
		return (strpos($format,'C') === 0);
368
	}
369
 
370
	public function estUnFormatRogne($format) {
371
		return (strpos($format,'R') === 1);
372
	}
373
 
374
	public function estPaysage($informations_images) {
375
		return $informations_images['largeur'] > $informations_images['hauteur'];
376
	}
377
 
378
	public function estPortait($informations_images) {
379
		return $informations_images['largeur'] < $informations_images['hauteur'];
380
	}
381
 
382
	public function renvoyerTauxCompressionPourPoids($poids_octets) {
970 aurelien 383
		$poids_max_octets = $this->config['cel']['taille_max'];
591 aurelien 384
 
385
		$ratio_compression = 100 ;
386
 
632 aurelien 387
	    if ($poids_octets >= $poids_max_octets) {
591 aurelien 388
	      $ratio_compression = 75 ;
389
	    }
390
 
391
	    return $ratio_compression;
392
	}
393
 
394
	public function convertirIdBddVersNomFichier($id, $format, $extension = 'jpg') {
672 jpm 395
		// creation du format original
591 aurelien 396
		$id_avec_zeros = sprintf('%09s', $id) ;
397
		$id_avec_zeros_underscores = wordwrap($id_avec_zeros, 3 , '_', true) ;
398
 
399
		$nom_fichier = $id_avec_zeros_underscores.'_'.$format.'.'.$extension;
400
 
401
		return $nom_fichier;
402
	}
403
 
404
	public function convertirBaseNomFichierVersIdBdd($nom_fichier, $formats) {
405
		$nom_fichier_sans_extension = trim($nom_fichier, '.jpg');
406
 
407
		foreach($formats as $format) {
408
			$nom_fichier_sans_extension = trim($nom_fichier_sans_extension, '_'.$format);
409
		}
410
 
411
		$id_image = str_replace('_', '', $nom_fichier_sans_extension);
412
 
413
		// suppression des 0 devant
414
		$id_image += 0;
415
 
416
		return $id_image;
417
	}
418
 
632 aurelien 419
	public function ecrireImageSurDisque($image_binaire, $id, $format, $compression = 100) {
591 aurelien 420
		umask(0);
421
 
422
		$chemin_sur_serveur_final = $this->creerSiNecessaireEtRenvoyerCheminStockageFichierPourIdEtFormat($id, $format);
423
		$nom_fichier = $this->convertirIdBddVersNomFichier($id, $format);
424
 
632 aurelien 425
		if (file_exists($chemin_sur_serveur_final.'/'.$nom_fichier)) {
591 aurelien 426
			unlink($chemin_sur_serveur_final.'/'.$nom_fichier);
427
		}
428
 
668 aurelien 429
		// attention, ceci ne preserve pas les metadonnées
632 aurelien 430
		imagejpeg($image_binaire, $chemin_sur_serveur_final.'/'.$nom_fichier, $compression);
591 aurelien 431
		chmod($chemin_sur_serveur_final.'/'.$nom_fichier,$this->droits);
432
	}
632 aurelien 433
 
434
	public function ecrireImageSurDisqueAvecMeta($image_a_stocker, $compression = 100) {
668 aurelien 435
		$image_a_stocker = new Imagick($image_a_stocker);
591 aurelien 436
 
632 aurelien 437
		// l'utilisation d'image magick préserve les métadonnées lors d'une recompression
438
		$image_a_stocker->setformat("jpeg");
439
		$image_a_stocker->setImageCompression(imagick::COMPRESSION_JPEG);
440
		$image_a_stocker->setCompressionQuality($compression);
668 aurelien 441
		$image_a_stocker->writeImage($image_a_stocker);
632 aurelien 442
		$image_a_stocker->destroy();
591 aurelien 443
 
668 aurelien 444
		chmod($image_a_stocker,$this->droits);
591 aurelien 445
	}
446
 
447
	public function renvoyerEtCreerImageCarreeBlancheSelonFormat($cote) {
448
		$image_blanche = imagecreatetruecolor($cote, $cote);
449
		$blanc = imagecolorallocate($image_blanche, 255, 255, 255);
450
		imagefilledrectangle($image_blanche, 0, 0, $cote, $cote, $blanc);
451
 
452
		return $image_blanche;
453
	}
454
 
455
	public function detruireImageEnMemoire($image) {
456
		imagedestroy($image);
457
	}
458
 
459
	public function detruireImageSurDisque($id) {
460
		$formats = $this->getFormats();
461
 
462
		// on detruit aussi l'image originale
463
		$formats[] = 'O';
464
 
621 aurelien 465
		$destruction_formats_fichier = false;
466
 
591 aurelien 467
		// destructions de chacuns des formats définis
468
		foreach($formats as $format) {
621 aurelien 469
 
591 aurelien 470
			$dossier_format = $this->obtenirDossierPourFormat($id, $format);
471
			$nom_fichier = $this->convertirIdBddVersNomFichier($id, $format);
621 aurelien 472
 
632 aurelien 473
			if (file_exists($dossier_format.'/'.$nom_fichier)) {
621 aurelien 474
				$destruction_formats_fichier = unlink($dossier_format.'/'.$nom_fichier);
475
			} else {
476
				$destruction_formats_fichier = true;
477
			}
591 aurelien 478
		}
621 aurelien 479
 
480
		return $destruction_formats_fichier;
591 aurelien 481
	}
632 aurelien 482
 
483
	/*
484
	 * edge-maximizing crop
485
	 * determines center-of-edginess, then tries different-sized crops around it.
486
	 * picks the crop with the highest normalized edginess.
487
	 * see documentation on how to tune the algorithm
488
	 *
489
	 * $informations_image - le tableau d'informations sur l'image tel que renvoyé par la fonction obtenirImageEtInfosPourChemin
490
	 * $format - le format (ex. : CS, XS, XL, CRS)
491
	*/
672 jpm 492
	public function opticrop($informations_image, $format) {
632 aurelien 493
		umask(0);
494
 
495
		$nom_temp = md5(time());
668 aurelien 496
		$chemin_temp =
632 aurelien 497
 
970 aurelien 498
		$out = $this->config['cel']['chemin_stockage_temp'].'/'.$nom_temp;
668 aurelien 499
 
632 aurelien 500
		$dimension_vignettes = $this->obtenirDimensionsPourFormat($format);
501
 
502
		$largeur_vignette = $dimension_vignettes['largeur'];
503
		$hauteur_vignette = $dimension_vignettes['hauteur'];
504
 
505
	    // source dimensions
506
	    $largeur_image_originale = $informations_image['largeur'];
507
	    $hauteur_image_originale = $informations_image['hauteur'];
508
 
509
	    $chemin_image = $informations_image['chemin'];
510
 
511
	    //if ($largeur_vignette > $largeur_image_originale || $hauteur_vignette > $hauteur_image_originale)
512
	    //    die("Target dimensions must be smaller or equal to source dimensions.");
513
 
514
	    // parameters for the edge-maximizing crop algorithm
515
	    $r = 1;         // radius of edge filter
516
	    $nk = 9;        // scale count: number of crop sizes to try
517
	    $gamma = 0.2;   // edge normalization parameter -- see documentation
518
	    $ar = $largeur_vignette/$hauteur_vignette;    // target aspect ratio (AR)
519
	    $ar0 = $largeur_image_originale/$hauteur_image_originale;    // original aspect ratio (AR)
520
 
521
	    //echo("$chemin_image: $largeur_image_originale x $hauteur_image_originale => $largeur_vignette x $hauteur_vignette");
522
	    $img = new Imagick($chemin_image);
523
	    $imgcp = clone $img;
524
 
525
	    // compute center of edginess
526
	    $img->edgeImage($r);
527
	    $img->modulateImage(100,0,100); // grayscale
528
	    $img->blackThresholdImage("#0f0f0f");
529
	    $img->writeImage($out);
530
	    // use gd for random pixel access
531
	    $im = ImageCreateFromJpeg($out);
532
	    $xcenter = 0;
533
	    $ycenter = 0;
534
	    $sum = 0;
535
	    $n = 100000;
536
	    for ($k=0; $k<$n; $k++) {
537
	        $i = mt_rand(0,$largeur_image_originale-1);
538
	        $j = mt_rand(0,$hauteur_image_originale-1);
539
	        $val = imagecolorat($im, $i, $j) & 0xFF;
540
	        $sum += $val;
541
	        $xcenter += ($i+1)*$val;
542
	        $ycenter += ($j+1)*$val;
543
	    }
544
	    $xcenter /= $sum;
545
	    $ycenter /= $sum;
546
 
547
	    // crop source img to target AR
548
	    if ($largeur_image_originale/$hauteur_image_originale > $ar) {
549
	        // source AR wider than target
550
	        // crop width to target AR
551
	        $wcrop0 = round($ar*$hauteur_image_originale);
552
	        $hcrop0 = $hauteur_image_originale;
672 jpm 553
	    } else {
632 aurelien 554
	        // crop height to target AR
555
	        $wcrop0 = $largeur_image_originale;
556
	        $hcrop0 = round($largeur_image_originale/$ar);
557
	    }
558
 
559
	    // crop parameters for all scales and translations
560
	    $params = array();
561
 
562
	    // crop at different scales
563
	    $hgap = $hcrop0 - $hauteur_vignette;
564
	    $hinc = ($nk == 1) ? 0 : $hgap / ($nk - 1);
565
	    $wgap = $wcrop0 - $largeur_vignette;
566
	    $winc = ($nk == 1) ? 0 : $wgap / ($nk - 1);
567
 
568
	    // find window with highest normalized edginess
569
	    $n = 10000;
570
	    $maxbetanorm = 0;
571
	    $maxfile = '';
572
	    $maxparam = array('w'=>0, 'h'=>0, 'x'=>0, 'y'=>0);
573
 
574
	    for ($k = 0; $k < $nk; $k++) {
575
	        $hcrop = round($hcrop0 - $k*$hinc);
576
	        $wcrop = round($wcrop0 - $k*$winc);
577
	        $xcrop = $xcenter - $wcrop / 2;
578
	        $ycrop = $ycenter - $hcrop / 2;
579
	        //echo("crop: $wcrop, $hcrop, $xcrop, $ycrop");
580
 
581
	        if ($xcrop < 0) $xcrop = 0;
582
	        if ($xcrop+$wcrop > $largeur_image_originale) $xcrop = $largeur_image_originale-$wcrop;
583
	        if ($ycrop < 0) $ycrop = 0;
584
	        if ($ycrop+$hcrop > $hauteur_image_originale) $ycrop = $hauteur_image_originale-$hcrop;
585
 
586
	        /*if (self::MODE_DEBUG) {
587
	        	// debug
588
	        	$currfile = '/home/aurelien/web/file_tmp/'."image$k.jpg";
589
 
590
	            $currimg = clone $img;
591
	            $c= new ImagickDraw();
592
	            $c->setFillColor("red");
593
	            $c->circle($xcenter, $ycenter, $xcenter, $ycenter+4);
594
	            $currimg->drawImage($c);
595
	            $currimg->cropImage($wcrop, $hcrop, $xcrop, $ycrop);
596
	            $currimg->writeImage($currfile);
597
	            $currimg->destroy();
598
	        }*/
599
 
600
	        $beta = 0;
601
	        for ($c=0; $c<$n; $c++) {
602
	            $i = mt_rand(0,$wcrop-1);
603
	            $j = mt_rand(0,$hcrop-1);
604
	            $beta += imagecolorat($im, $xcrop+$i, $ycrop+$j) & 0xFF;
605
	        }
606
	        $area = $wcrop * $hcrop;
607
	        $betanorm = $beta / ($n*pow($area, $gamma-1));
608
	        // echo("beta: $beta; betan: $betanorm");
609
	        // echo("image$k.jpg:<br/>\n<img src=\"$currfile\"/>");
610
	        // best image found, save it
611
 
612
	        if ($betanorm > $maxbetanorm) {
613
 
614
	            $maxbetanorm = $betanorm;
615
	            $maxparam['w'] = $wcrop;
616
	            $maxparam['h'] = $hcrop;
617
	            $maxparam['x'] = $xcrop;
618
	            $maxparam['y'] = $ycrop;
619
	            // $maxfile = $currfile;
620
	        }
621
	    }
622
 
623
        // return image
624
        $imgcp->cropImage($maxparam['w'], $maxparam['h'], $maxparam['x'], $maxparam['y']);
625
        $imgcp->scaleImage($largeur_vignette, $hauteur_vignette);
626
        $imgcp->writeImage($out);
627
	    chmod($out, 0777);
628
	    $img->destroy();
629
	    $imgcp->destroy();
630
 
631
	    $image_sortie = ImageCreateFromJpeg($out);
632
	    unlink($out);
633
 
634
	    return $image_sortie;
635
	}
591 aurelien 636
}
637
?>