Subversion Repositories eFlore/Applications.cel

Rev

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

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