Subversion Repositories eFlore/Applications.cel

Rev

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

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