Subversion Repositories eFlore/Applications.cel

Rev

Rev 2238 | Go to most recent revision | Only display areas with differences | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

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