Subversion Repositories eFlore/Applications.cel

Rev

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

Rev 3460 Rev 3786
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'], $image_et_infos['imagetype']) = getimagesize($chemin_fichier);
419
			list($image_et_infos['largeur'], $image_et_infos['hauteur'], $image_et_infos['imagetype']) = getimagesize($chemin_fichier);
420
			$image_et_infos['poids_octets'] = filesize($chemin_fichier);
420
			$image_et_infos['poids_octets'] = filesize($chemin_fichier);
421
			$image_et_infos['chemin'] = $chemin_fichier;
421
			$image_et_infos['chemin'] = $chemin_fichier;
422
 
422
 
423
			switch (image_type_to_mime_type($image_et_infos['imagetype'])) {
423
			switch (image_type_to_mime_type($image_et_infos['imagetype'])) {
424
				case 'image/jpeg':
424
				case 'image/jpeg':
425
					$image_et_infos['image'] = imagecreatefromjpeg($chemin_fichier);
425
					$image_et_infos['image'] = imagecreatefromjpeg($chemin_fichier);
426
					break;
426
					break;
427
				case 'image/png':
427
				case 'image/png':
428
					$image_et_infos['image'] = imagecreatefrompng($chemin_fichier);
428
					$image_et_infos['image'] = imagecreatefrompng($chemin_fichier);
429
					break;
429
					break;
430
				default:
430
				default:
431
					// ni jpeg ni png donc pas supporté, ça dégage
431
					// ni jpeg ni png donc pas supporté, ça dégage
432
					return false;
432
					return false;
433
			}
433
			}
434
		}
434
		}
435
		return $image_et_infos;
435
		return $image_et_infos;
436
	}
436
	}
437
 
437
 
438
	public function obtenirDimensionsPourFormat($format) {
438
	public function obtenirDimensionsPourFormat($format) {
439
		$dimensions = array('largeur' => 0, 'hauteur' => 0);
439
		$dimensions = array('largeur' => 0, 'hauteur' => 0);
440
 
440
 
441
		if (isset($this->config['cel']['format_'.$format])) {
441
		if (isset($this->config['cel']['format_'.$format])) {
442
			list($dimensions['largeur'], $dimensions['hauteur']) = explode('_', $this->config['cel']['format_'.$format]);
442
			list($dimensions['largeur'], $dimensions['hauteur']) = explode('_', $this->config['cel']['format_'.$format]);
443
		}
443
		}
444
 
444
 
445
		return $dimensions;
445
		return $dimensions;
446
	}
446
	}
447
 
447
 
448
	public function calculerTailleImage($informations_images, $taille_max) {
448
	public function calculerTailleImage($informations_images, $taille_max) {
449
		$HL_redimension = array();
449
		$HL_redimension = array();
450
 
450
 
451
		if ($this->estPaysage($informations_images)) {
451
		if ($this->estPaysage($informations_images)) {
452
			$rapport = $informations_images['hauteur']/$informations_images['largeur'] ;
452
			$rapport = $informations_images['hauteur']/$informations_images['largeur'] ;
453
			$HL_redimension['largeur'] = round($taille_max) ;
453
			$HL_redimension['largeur'] = round($taille_max) ;
454
			$HL_redimension['hauteur'] = round($taille_max*$rapport) ;
454
			$HL_redimension['hauteur'] = round($taille_max*$rapport) ;
455
 
455
 
456
		} else {
456
		} else {
457
			// protection contre division par 0 - prob. symptôme d'un autre pb : image vide ou mal transmise,
457
			// protection contre division par 0 - prob. symptôme d'un autre pb : image vide ou mal transmise,
458
			// voir TODO dans obtenirImageEtInfosPourChemin()
458
			// voir TODO dans obtenirImageEtInfosPourChemin()
459
			$rapport = $informations_images['hauteur'] == 0 ? 0 : $informations_images['largeur'] / $informations_images['hauteur'];
459
			$rapport = $informations_images['hauteur'] == 0 ? 0 : $informations_images['largeur'] / $informations_images['hauteur'];
460
			$HL_redimension['hauteur'] = round($taille_max) ;
460
			$HL_redimension['hauteur'] = round($taille_max) ;
461
			$HL_redimension['largeur'] = round($taille_max*$rapport) ;
461
			$HL_redimension['largeur'] = round($taille_max*$rapport) ;
462
		}
462
		}
463
 
463
 
464
		return $HL_redimension;
464
		return $HL_redimension;
465
	}
465
	}
466
 
466
 
467
	public function getFormats() {
467
	public function getFormats() {
468
		return $this->formats;
468
		return $this->formats;
469
	}
469
	}
470
 
470
 
471
	public function estUnFormatCarre($format) {
471
	public function estUnFormatCarre($format) {
472
		return (strpos($format,'C') === 0);
472
		return (strpos($format,'C') === 0);
473
	}
473
	}
474
 
474
 
475
	public function estUnFormatRogne($format) {
475
	public function estUnFormatRogne($format) {
476
		return (strpos($format,'R') === 1);
476
		return (strpos($format,'R') === 1);
477
	}
477
	}
478
 
478
 
479
	public function estPaysage($informations_images) {
479
	public function estPaysage($informations_images) {
480
		return $informations_images['largeur'] > $informations_images['hauteur'];
480
		return $informations_images['largeur'] > $informations_images['hauteur'];
481
	}
481
	}
482
 
482
 
483
	public function estPortait($informations_images) {
483
	public function estPortait($informations_images) {
484
		return $informations_images['largeur'] < $informations_images['hauteur'];
484
		return $informations_images['largeur'] < $informations_images['hauteur'];
485
	}
485
	}
486
 
486
 
487
	public function renvoyerTauxCompressionPourPoids($poids_octets) {
487
	public function renvoyerTauxCompressionPourPoids($poids_octets) {
488
		$poids_max_octets = $this->config['cel']['taille_max'];
488
		$poids_max_octets = $this->config['cel']['taille_max'];
489
 
489
 
490
		$ratio_compression = 100 ;
490
		$ratio_compression = 100 ;
491
 
491
 
492
		if ($poids_octets >= $poids_max_octets) {
492
		if ($poids_octets >= $poids_max_octets) {
493
			$ratio_compression = 75 ;
493
			$ratio_compression = 75 ;
494
		}
494
		}
495
 
495
 
496
		return $ratio_compression;
496
		return $ratio_compression;
497
	}
497
	}
498
 
498
 
499
	public function convertirIdBddVersNomFichier($id, $format, $extension = 'jpg') {
499
	public function convertirIdBddVersNomFichier($id, $format, $extension = 'jpg') {
500
		// creation du format original
500
		// creation du format original
501
		$id_avec_zeros = sprintf('%09s', $id);
501
		$id_avec_zeros = sprintf('%09s', $id);
502
		$id_avec_zeros_underscores = wordwrap($id_avec_zeros, 3 , '_', true);
502
		$id_avec_zeros_underscores = wordwrap($id_avec_zeros, 3 , '_', true);
503
 
503
 
504
		// déterminationnage de l'extension
504
		// déterminationnage de l'extension
505
		$path = $this->obtenirDossierPourFormat($id, $format);
505
		$path = $this->obtenirDossierPourFormat($id, $format);
506
		foreach(['jpg', 'JPG', 'png', 'PNG'] as $ext) {
506
		foreach(['jpg', 'JPG', 'jpeg', 'JPEG', 'png', 'PNG'] as $ext) {
507
			if (file_exists($path.'/'.$id_avec_zeros_underscores.'_'.$format.'.'.$ext)) {
507
			if (file_exists($path.'/'.$id_avec_zeros_underscores.'_'.$format.'.'.$ext)) {
508
				$extension = $ext;
508
				$extension = $ext;
509
				break;
509
				break;
510
			}
510
			}
511
		}
511
		}
512
 
512
 
513
		$nom_fichier = $id_avec_zeros_underscores.'_'.$format.'.'.$extension;
513
		$nom_fichier = $id_avec_zeros_underscores.'_'.$format.'.'.$extension;
514
 
514
 
515
		return $nom_fichier;
515
		return $nom_fichier;
516
	}
516
	}
517
 
517
 
518
	public function convertirBaseNomFichierVersIdBdd($nom_fichier, $formats) {
518
	public function convertirBaseNomFichierVersIdBdd($nom_fichier, $formats) {
519
		$nom_fichier_sans_extension = trim($nom_fichier, '.jpg');
519
		$nom_fichier_sans_extension = trim($nom_fichier, '.jpg');
520
 
520
 
521
		foreach ($formats as $format) {
521
		foreach ($formats as $format) {
522
			$nom_fichier_sans_extension = trim($nom_fichier_sans_extension, '_'.$format);
522
			$nom_fichier_sans_extension = trim($nom_fichier_sans_extension, '_'.$format);
523
		}
523
		}
524
		$id_image = str_replace('_', '', $nom_fichier_sans_extension);
524
		$id_image = str_replace('_', '', $nom_fichier_sans_extension);
525
 
525
 
526
		// suppression des 0 devant
526
		// suppression des 0 devant
527
		$id_image += 0;
527
		$id_image += 0;
528
 
528
 
529
		return $id_image;
529
		return $id_image;
530
	}
530
	}
531
 
531
 
532
	public function ecrireImageSurDisque($image_binaire, $id, $format, $compression = 100) {
532
	public function ecrireImageSurDisque($image_binaire, $id, $format, $compression = 100) {
533
		umask(0);
533
		umask(0);
534
 
534
 
535
		$chemin_sur_serveur_final = $this->creerSiNecessaireEtRenvoyerCheminStockageFichierPourIdEtFormat($id, $format);
535
		$chemin_sur_serveur_final = $this->creerSiNecessaireEtRenvoyerCheminStockageFichierPourIdEtFormat($id, $format);
536
		$nom_fichier = $this->convertirIdBddVersNomFichier($id, $format);
536
		$nom_fichier = $this->convertirIdBddVersNomFichier($id, $format);
537
 
537
 
538
		if (file_exists($chemin_sur_serveur_final.'/'.$nom_fichier)) {
538
		if (file_exists($chemin_sur_serveur_final.'/'.$nom_fichier)) {
539
			unlink($chemin_sur_serveur_final.'/'.$nom_fichier);
539
			unlink($chemin_sur_serveur_final.'/'.$nom_fichier);
540
		}
540
		}
541
 
541
 
542
		// attention, ceci ne preserve pas les metadonnées
542
		// attention, ceci ne preserve pas les metadonnées
543
		imagejpeg($image_binaire, $chemin_sur_serveur_final.'/'.$nom_fichier, $compression);
543
		imagejpeg($image_binaire, $chemin_sur_serveur_final.'/'.$nom_fichier, $compression);
544
		chmod($chemin_sur_serveur_final.'/'.$nom_fichier,$this->droits);
544
		chmod($chemin_sur_serveur_final.'/'.$nom_fichier,$this->droits);
545
	}
545
	}
546
 
546
 
547
	public function ecrireImageSurDisqueAvecMeta($chemin_image_a_stocker, $compression = 100) {
547
	public function ecrireImageSurDisqueAvecMeta($chemin_image_a_stocker, $compression = 100) {
548
		try {
548
		try {
549
			$img = new Imagick($chemin_image_a_stocker);
549
			$img = new Imagick($chemin_image_a_stocker);
550
 
550
 
551
			// l'utilisation d'image magick préserve les métadonnées lors d'une recompression
551
			// l'utilisation d'image magick préserve les métadonnées lors d'une recompression
552
			$img->setformat('jpeg');
552
			$img->setformat('jpeg');
553
			$img->setImageCompression(imagick::COMPRESSION_JPEG);
553
			$img->setImageCompression(imagick::COMPRESSION_JPEG);
554
			$img->setCompressionQuality($compression);
554
			$img->setCompressionQuality($compression);
555
			$img->writeImage($chemin_image_a_stocker);
555
			$img->writeImage($chemin_image_a_stocker);
556
			$img->destroy();
556
			$img->destroy();
557
	
557
	
558
			chmod($chemin_image_a_stocker, $this->droits);
558
			chmod($chemin_image_a_stocker, $this->droits);
559
			return true;
559
			return true;
560
		} catch (ImagickException $e) {
560
		} catch (ImagickException $e) {
561
			return false;
561
			return false;
562
		}
562
		}
563
	}
563
	}
564
 
564
 
565
	public function renvoyerEtCreerImageCarreeBlancheSelonFormat($cote) {
565
	public function renvoyerEtCreerImageCarreeBlancheSelonFormat($cote) {
566
		$image_blanche = imagecreatetruecolor($cote, $cote);
566
		$image_blanche = imagecreatetruecolor($cote, $cote);
567
		$blanc = imagecolorallocate($image_blanche, 255, 255, 255);
567
		$blanc = imagecolorallocate($image_blanche, 255, 255, 255);
568
		imagefilledrectangle($image_blanche, 0, 0, $cote, $cote, $blanc);
568
		imagefilledrectangle($image_blanche, 0, 0, $cote, $cote, $blanc);
569
		return $image_blanche;
569
		return $image_blanche;
570
	}
570
	}
571
 
571
 
572
	public function detruireImageEnMemoire($image) {
572
	public function detruireImageEnMemoire($image) {
573
		imagedestroy($image);
573
		imagedestroy($image);
574
	}
574
	}
575
 
575
 
576
	/**
576
	/**
577
	 * Supprime une image du disque, ainsi que tous les formats générés
577
	 * Supprime une image du disque, ainsi que tous les formats générés
578
	 *
578
	 *
579
	 * @param Integer $id
579
	 * @param Integer $id
580
	 * @return boolean true si tous les formats y compris l'original ont été détruits, false s'il en reste au moins un
580
	 * @return boolean true si tous les formats y compris l'original ont été détruits, false s'il en reste au moins un
581
	 */
581
	 */
582
	public function detruireImageSurDisque($id) {
582
	public function detruireImageSurDisque($id) {
583
		$formats = $this->getFormats();
583
		$formats = $this->getFormats();
584
		// on detruit aussi l'image originale
584
		// on detruit aussi l'image originale
585
		$formats[] = 'O';
585
		$formats[] = 'O';
586
 
586
 
587
		$destruction_formats_fichier = true;
587
		$destruction_formats_fichier = true;
588
		// destructions de chacun des formats définis
588
		// destructions de chacun des formats définis
589
		foreach($formats as $format) {
589
		foreach($formats as $format) {
590
			$dossier_format = $this->obtenirDossierPourFormat($id, $format);
590
			$dossier_format = $this->obtenirDossierPourFormat($id, $format);
591
			$nom_fichier = $this->convertirIdBddVersNomFichier($id, $format);
591
			$nom_fichier = $this->convertirIdBddVersNomFichier($id, $format);
592
 
592
 
593
			if (file_exists($dossier_format.'/'.$nom_fichier)) {
593
			if (file_exists($dossier_format.'/'.$nom_fichier)) {
594
				$detruit = unlink($dossier_format.'/'.$nom_fichier);
594
				$detruit = unlink($dossier_format.'/'.$nom_fichier);
595
				$destruction_formats_fichier = ($destruction_formats_fichier && $detruit);
595
				$destruction_formats_fichier = ($destruction_formats_fichier && $detruit);
596
			}
596
			}
597
		}
597
		}
598
 
598
 
599
		return $destruction_formats_fichier;
599
		return $destruction_formats_fichier;
600
	}
600
	}
601
 
601
 
602
	// recopie de Cel->logger() (pas d'extends pour ça)
602
	// recopie de Cel->logger() (pas d'extends pour ça)
603
	public function logger($index,$chaine) {
603
	public function logger($index,$chaine) {
604
		if (!class_exists('Log')) {
604
		if (!class_exists('Log')) {
605
			Log::getInstance();
605
			Log::getInstance();
606
		}
606
		}
607
 
607
 
608
		Log::setCheminLog($this->config['log']['cheminlog']);
608
		Log::setCheminLog($this->config['log']['cheminlog']);
609
		Log::setTimeZone($this->config['log']['timezone']);
609
		Log::setTimeZone($this->config['log']['timezone']);
610
		Log::setTailleMax($this->config['log']['taillemax']);
610
		Log::setTailleMax($this->config['log']['taillemax']);
611
 
611
 
612
		Log::ajouterEntree($index,$chaine);
612
		Log::ajouterEntree($index,$chaine);
613
	}
613
	}
614
 
614
 
615
	/*
615
	/*
616
	 * edge-maximizing crop
616
	 * edge-maximizing crop
617
	 * determines center-of-edginess, then tries different-sized crops around it.
617
	 * determines center-of-edginess, then tries different-sized crops around it.
618
	 * picks the crop with the highest normalized edginess.
618
	 * picks the crop with the highest normalized edginess.
619
	 * see documentation on how to tune the algorithm
619
	 * see documentation on how to tune the algorithm
620
	 *
620
	 *
621
	 * $informations_image - le tableau d'informations sur l'image tel que renvoyé par la fonction obtenirImageEtInfosPourChemin
621
	 * $informations_image - le tableau d'informations sur l'image tel que renvoyé par la fonction obtenirImageEtInfosPourChemin
622
	 * $format - le format (ex. : CS, XS, XL, CRS)
622
	 * $format - le format (ex. : CS, XS, XL, CRS)
623
	*/
623
	*/
624
	public function opticrop($informations_image, $format) {
624
	public function opticrop($informations_image, $format) {
625
		umask(0);
625
		umask(0);
626
		$erreur_ecriture = false;
626
		$erreur_ecriture = false;
627
 
627
 
628
		$nom_temp = md5(time());
628
		$nom_temp = md5(time());
629
		$chemin_temp =
629
		$chemin_temp =
630
 
630
 
631
		$out = $this->config['cel']['chemin_stockage_temp'].'/'.$nom_temp;
631
		$out = $this->config['cel']['chemin_stockage_temp'].'/'.$nom_temp;
632
 
632
 
633
		$dimension_vignettes = $this->obtenirDimensionsPourFormat($format);
633
		$dimension_vignettes = $this->obtenirDimensionsPourFormat($format);
634
 
634
 
635
		$largeur_vignette = $dimension_vignettes['largeur'];
635
		$largeur_vignette = $dimension_vignettes['largeur'];
636
		$hauteur_vignette = $dimension_vignettes['hauteur'];
636
		$hauteur_vignette = $dimension_vignettes['hauteur'];
637
 
637
 
638
		// source dimensions
638
		// source dimensions
639
		$largeur_image_originale = $informations_image['largeur'];
639
		$largeur_image_originale = $informations_image['largeur'];
640
		$hauteur_image_originale = $informations_image['hauteur'];
640
		$hauteur_image_originale = $informations_image['hauteur'];
641
 
641
 
642
		$chemin_image = $informations_image['chemin'];
642
		$chemin_image = $informations_image['chemin'];
643
 
643
 
644
		// parameters for the edge-maximizing crop algorithm
644
		// parameters for the edge-maximizing crop algorithm
645
		$r = 1;         // radius of edge filter
645
		$r = 1;         // radius of edge filter
646
		$nk = 9;        // scale count: number of crop sizes to try
646
		$nk = 9;        // scale count: number of crop sizes to try
647
		$gamma = 0.2;   // edge normalization parameter -- see documentation
647
		$gamma = 0.2;   // edge normalization parameter -- see documentation
648
		$ar = $largeur_vignette/$hauteur_vignette;    // target aspect ratio (AR)
648
		$ar = $largeur_vignette/$hauteur_vignette;    // target aspect ratio (AR)
649
		$ar0 = $largeur_image_originale/$hauteur_image_originale;    // original aspect ratio (AR)
649
		$ar0 = $largeur_image_originale/$hauteur_image_originale;    // original aspect ratio (AR)
650
 
650
 
651
		//echo("$chemin_image: $largeur_image_originale x $hauteur_image_originale => $largeur_vignette x $hauteur_vignette");
651
		//echo("$chemin_image: $largeur_image_originale x $hauteur_image_originale => $largeur_vignette x $hauteur_vignette");
652
		try {
652
		try {
653
			$img = new Imagick($chemin_image); // ce machin jette une ImagickException si le fichier est vide
653
			$img = new Imagick($chemin_image); // ce machin jette une ImagickException si le fichier est vide
654
			$imgcp = clone $img;
654
			$imgcp = clone $img;
655
			// compute center of edginess
655
			// compute center of edginess
656
			$img->edgeImage($r);
656
			$img->edgeImage($r);
657
			$img->modulateImage(100,0,100); // grayscale
657
			$img->modulateImage(100,0,100); // grayscale
658
			$img->blackThresholdImage("#0f0f0f");
658
			$img->blackThresholdImage("#0f0f0f");
659
			$retour_ecriture_img = $img->writeImage($out);
659
			$retour_ecriture_img = $img->writeImage($out);
660
 
660
 
661
			if ($retour_ecriture_img !== true) {
661
			if ($retour_ecriture_img !== true) {
662
				error_log("Erreur d'écriture Imagick : [" . $chemin_image . "] vers [" . $out . "]");
662
				error_log("Erreur d'écriture Imagick : [" . $chemin_image . "] vers [" . $out . "]");
663
				$erreur_ecriture = true;
663
				$erreur_ecriture = true;
664
			}
664
			}
665
			// use gd for random pixel access
665
			// use gd for random pixel access
666
			$im = ImageCreateFromJpeg($out);
666
			$im = ImageCreateFromJpeg($out);
667
	
667
	
668
			if ($im === false) {
668
			if ($im === false) {
669
				error_log("GD ne peut pas lire l'image créée par Imagick : [" . $chemin_image . "] vers [" . $out . "]");
669
				error_log("GD ne peut pas lire l'image créée par Imagick : [" . $chemin_image . "] vers [" . $out . "]");
670
				$erreur_ecriture = true;
670
				$erreur_ecriture = true;
671
			}
671
			}
672
		} catch (ImagickException $e) {
672
		} catch (ImagickException $e) {
673
			// En principe si on se trouve ici c'est que l'image est vide 
673
			// En principe si on se trouve ici c'est que l'image est vide 
674
			$erreur_ecriture = true;
674
			$erreur_ecriture = true;
675
			$image_sortie = false;
675
			$image_sortie = false;
676
		}
676
		}
677
 
677
 
678
		if (! $erreur_ecriture) {
678
		if (! $erreur_ecriture) {
679
			$xcenter = 0;
679
			$xcenter = 0;
680
			$ycenter = 0;
680
			$ycenter = 0;
681
			$sum = 0;
681
			$sum = 0;
682
			$n = 100000;
682
			$n = 100000;
683
			for ($k=0; $k<$n; $k++) {
683
			for ($k=0; $k<$n; $k++) {
684
				$i = mt_rand(0,$largeur_image_originale-1);
684
				$i = mt_rand(0,$largeur_image_originale-1);
685
				$j = mt_rand(0,$hauteur_image_originale-1);
685
				$j = mt_rand(0,$hauteur_image_originale-1);
686
				$val = imagecolorat($im, $i, $j) & 0xFF;
686
				$val = imagecolorat($im, $i, $j) & 0xFF;
687
				$sum += $val;
687
				$sum += $val;
688
				$xcenter += ($i+1)*$val;
688
				$xcenter += ($i+1)*$val;
689
				$ycenter += ($j+1)*$val;
689
				$ycenter += ($j+1)*$val;
690
			}
690
			}
691
			$xcenter /= $sum;
691
			$xcenter /= $sum;
692
			$ycenter /= $sum;
692
			$ycenter /= $sum;
693
 
693
 
694
			// crop source img to target AR
694
			// crop source img to target AR
695
			if ($largeur_image_originale/$hauteur_image_originale > $ar) {
695
			if ($largeur_image_originale/$hauteur_image_originale > $ar) {
696
				// source AR wider than target
696
				// source AR wider than target
697
				// crop width to target AR
697
				// crop width to target AR
698
				$wcrop0 = round($ar*$hauteur_image_originale);
698
				$wcrop0 = round($ar*$hauteur_image_originale);
699
				$hcrop0 = $hauteur_image_originale;
699
				$hcrop0 = $hauteur_image_originale;
700
			} else {
700
			} else {
701
				// source AR wider than target
701
				// source AR wider than target
702
				// crop height to target AR
702
				// crop height to target AR
703
				$wcrop0 = $largeur_image_originale;
703
				$wcrop0 = $largeur_image_originale;
704
				$hcrop0 = round($largeur_image_originale/$ar);
704
				$hcrop0 = round($largeur_image_originale/$ar);
705
			}
705
			}
706
 
706
 
707
			// crop parameters for all scales and translations
707
			// crop parameters for all scales and translations
708
			$params = array();
708
			$params = array();
709
 
709
 
710
			// crop at different scales
710
			// crop at different scales
711
			$hgap = $hcrop0 - $hauteur_vignette;
711
			$hgap = $hcrop0 - $hauteur_vignette;
712
			$hinc = ($nk == 1) ? 0 : $hgap / ($nk - 1);
712
			$hinc = ($nk == 1) ? 0 : $hgap / ($nk - 1);
713
			$wgap = $wcrop0 - $largeur_vignette;
713
			$wgap = $wcrop0 - $largeur_vignette;
714
			$winc = ($nk == 1) ? 0 : $wgap / ($nk - 1);
714
			$winc = ($nk == 1) ? 0 : $wgap / ($nk - 1);
715
 
715
 
716
			// find window with highest normalized edginess
716
			// find window with highest normalized edginess
717
			$n = 10000;
717
			$n = 10000;
718
			$maxbetanorm = 0;
718
			$maxbetanorm = 0;
719
			$maxfile = '';
719
			$maxfile = '';
720
			$maxparam = array('w'=>0, 'h'=>0, 'x'=>0, 'y'=>0);
720
			$maxparam = array('w'=>0, 'h'=>0, 'x'=>0, 'y'=>0);
721
 
721
 
722
			for ($k = 0; $k < $nk; $k++) {
722
			for ($k = 0; $k < $nk; $k++) {
723
				$hcrop = round($hcrop0 - $k*$hinc);
723
				$hcrop = round($hcrop0 - $k*$hinc);
724
				$wcrop = round($wcrop0 - $k*$winc);
724
				$wcrop = round($wcrop0 - $k*$winc);
725
				$xcrop = $xcenter - $wcrop / 2;
725
				$xcrop = $xcenter - $wcrop / 2;
726
				$ycrop = $ycenter - $hcrop / 2;
726
				$ycrop = $ycenter - $hcrop / 2;
727
				//echo("crop: $wcrop, $hcrop, $xcrop, $ycrop");
727
				//echo("crop: $wcrop, $hcrop, $xcrop, $ycrop");
728
 
728
 
729
				if ($xcrop < 0) $xcrop = 0;
729
				if ($xcrop < 0) $xcrop = 0;
730
				if ($xcrop+$wcrop > $largeur_image_originale) $xcrop = $largeur_image_originale-$wcrop;
730
				if ($xcrop+$wcrop > $largeur_image_originale) $xcrop = $largeur_image_originale-$wcrop;
731
				if ($ycrop < 0) $ycrop = 0;
731
				if ($ycrop < 0) $ycrop = 0;
732
				if ($ycrop+$hcrop > $hauteur_image_originale) $ycrop = $hauteur_image_originale-$hcrop;
732
				if ($ycrop+$hcrop > $hauteur_image_originale) $ycrop = $hauteur_image_originale-$hcrop;
733
 
733
 
734
				$beta = 0;
734
				$beta = 0;
735
				for ($c=0; $c<$n; $c++) {
735
				for ($c=0; $c<$n; $c++) {
736
					$i = mt_rand(0,$wcrop-1);
736
					$i = mt_rand(0,$wcrop-1);
737
					$j = mt_rand(0,$hcrop-1);
737
					$j = mt_rand(0,$hcrop-1);
738
					$beta += imagecolorat($im, $xcrop+$i, $ycrop+$j) & 0xFF;
738
					$beta += imagecolorat($im, $xcrop+$i, $ycrop+$j) & 0xFF;
739
				}
739
				}
740
				$area = $wcrop * $hcrop;
740
				$area = $wcrop * $hcrop;
741
				$betanorm = $beta / ($n*pow($area, $gamma-1));
741
				$betanorm = $beta / ($n*pow($area, $gamma-1));
742
				// echo("beta: $beta; betan: $betanorm");
742
				// echo("beta: $beta; betan: $betanorm");
743
				// echo("image$k.jpg:<br/>\n<img src=\"$currfile\"/>");
743
				// echo("image$k.jpg:<br/>\n<img src=\"$currfile\"/>");
744
				// best image found, save it
744
				// best image found, save it
745
 
745
 
746
				if ($betanorm > $maxbetanorm) {
746
				if ($betanorm > $maxbetanorm) {
747
 
747
 
748
					$maxbetanorm = $betanorm;
748
					$maxbetanorm = $betanorm;
749
					$maxparam['w'] = $wcrop;
749
					$maxparam['w'] = $wcrop;
750
					$maxparam['h'] = $hcrop;
750
					$maxparam['h'] = $hcrop;
751
					$maxparam['x'] = $xcrop;
751
					$maxparam['x'] = $xcrop;
752
					$maxparam['y'] = $ycrop;
752
					$maxparam['y'] = $ycrop;
753
					// $maxfile = $currfile;
753
					// $maxfile = $currfile;
754
				}
754
				}
755
			}
755
			}
756
 
756
 
757
			// écrasement de l'image par la version "croppée"
757
			// écrasement de l'image par la version "croppée"
758
			$imgcp->cropImage($maxparam['w'], $maxparam['h'], $maxparam['x'], $maxparam['y']);
758
			$imgcp->cropImage($maxparam['w'], $maxparam['h'], $maxparam['x'], $maxparam['y']);
759
			// retailler correctement si au moins une des dimensions de l'image produite est
759
			// retailler correctement si au moins une des dimensions de l'image produite est
760
			// inférieure aux dimensions demandées
760
			// inférieure aux dimensions demandées
761
			$geo = $imgcp->getImageGeometry();
761
			$geo = $imgcp->getImageGeometry();
762
			$ratio_la = $geo['width'] / $largeur_vignette;
762
			$ratio_la = $geo['width'] / $largeur_vignette;
763
			$ratio_ha = $geo['height'] / $hauteur_vignette;
763
			$ratio_ha = $geo['height'] / $hauteur_vignette;
764
			if ($ratio_la < 1 || $ratio_ha < 1) {
764
			if ($ratio_la < 1 || $ratio_ha < 1) {
765
				// cas kipu - on agrandit au max la dimension ayant le ratio le plus faible
765
				// cas kipu - on agrandit au max la dimension ayant le ratio le plus faible
766
				// (= le plus d'écart avec la taille attendue)
766
				// (= le plus d'écart avec la taille attendue)
767
				if ($ratio_la < $ratio_ha) {
767
				if ($ratio_la < $ratio_ha) {
768
					$imgcp->scaleImage($largeur_vignette, 0);
768
					$imgcp->scaleImage($largeur_vignette, 0);
769
				} else {
769
				} else {
770
					$imgcp->scaleImage(0, $hauteur_vignette);
770
					$imgcp->scaleImage(0, $hauteur_vignette);
771
				}
771
				}
772
				// puis on recoupe en centrant à l'arrache - bizarre que le script ne fasse pas ça de base :-/
772
				// puis on recoupe en centrant à l'arrache - bizarre que le script ne fasse pas ça de base :-/
773
				$geo = $imgcp->getImageGeometry();
773
				$geo = $imgcp->getImageGeometry();
774
				$imgcp->cropImage($largeur_vignette, $hauteur_vignette, max(0, floor($geo['width'] / 2 - $largeur_vignette / 2)), max(0, floor($geo['height'] / 2 - $hauteur_vignette / 2)));
774
				$imgcp->cropImage($largeur_vignette, $hauteur_vignette, max(0, floor($geo['width'] / 2 - $largeur_vignette / 2)), max(0, floor($geo['height'] / 2 - $hauteur_vignette / 2)));
775
			} else {
775
			} else {
776
				// cas général
776
				// cas général
777
				$imgcp->scaleImage($largeur_vignette, $hauteur_vignette, false);
777
				$imgcp->scaleImage($largeur_vignette, $hauteur_vignette, false);
778
			}
778
			}
779
			$imgcp->writeImage($out);
779
			$imgcp->writeImage($out);
780
 
780
 
781
			// return image
781
			// return image
782
			chmod($out, 0777);
782
			chmod($out, 0777);
783
			$img->destroy();
783
			$img->destroy();
784
			$imgcp->destroy();
784
			$imgcp->destroy();
785
			$image_sortie = ImageCreateFromJpeg($out);
785
			$image_sortie = ImageCreateFromJpeg($out);
786
		} else {
786
		} else {
787
			// image n'a pas pu être croppée - on retourne l'originale
787
			// image n'a pas pu être croppée - on retourne l'originale
788
			//$image_sortie = ImageCreateFromJpeg($chemin_image);
788
			//$image_sortie = ImageCreateFromJpeg($chemin_image);
789
			$image_sortie = false;
789
			$image_sortie = false;
790
		}
790
		}
791
 
791
 
792
		// destruction fichier temporaire dans tous les cas
792
		// destruction fichier temporaire dans tous les cas
793
		unlink($out);
793
		unlink($out);
794
 
794
 
795
		return $image_sortie;
795
		return $image_sortie;
796
	}
796
	}
797
}
797
}