Subversion Repositories eFlore/Applications.cel

Rev

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