Subversion Repositories eFlore/Applications.cel

Rev

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

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