Subversion Repositories eFlore/Applications.cel

Rev

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

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