Subversion Repositories eFlore/Applications.cel

Rev

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

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