Subversion Repositories eFlore/Applications.cel

Rev

Rev 3912 | Only display areas with differences | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

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