Subversion Repositories eFlore/Applications.cel

Rev

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

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