Subversion Repositories eFlore/Applications.cel

Compare Revisions

Ignore whitespace Rev 2461 → Rev 2462

/trunk/jrest/bibliotheque/ImageRecreation.php
1,4 → 1,20
<?php
// declare(encoding='UTF-8');
/**
* Classe de manipulation des fichiers images JPEG.
*
* @internal Mininum PHP version : 5.2
* @category CEL
* @package Services
* @subpackage Bibliothèques
* @version 0.1
* @author Mathias CHOUET <mathias@tela-botanica.org>
* @author Jean-Pascal MILCENT <jpm@tela-botanica.org>
* @author Aurelien PERONNET <aurelien@tela-botanica.org>
* @license GPL v3 <http://www.gnu.org/licenses/gpl.txt>
* @license CECILL v2 <http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt>
* @copyright 1999-2014 Tela Botanica <accueil@tela-botanica.org>
*/
Class ImageRecreation {
 
private $droits = 0755;
39,7 → 55,7
$id = $params[0];
 
if (!is_numeric($id)) {
return;
return;
}
 
$dossier_fichier = $this->obtenirDossierPourFormat($id, 'O');
54,7 → 70,6
foreach ($this->formats as $format) {
$this->creerEtStockerMiniatureFichierImageSelonFormat($id, $infos_image_originale, $format);
};
 
}
}
 
71,37 → 86,37
continue;
}
 
if ($fichier_ou_dossier->isDir()) {
$this->itererRecursivement($fichier_ou_dossier->getPathname());
} else {
$nom_fichier = $fichier_ou_dossier->getFilename();
if ($fichier_ou_dossier->isDir()) {
$this->itererRecursivement($fichier_ou_dossier->getPathname());
} else {
$nom_fichier = $fichier_ou_dossier->getFilename();
 
$infos_image_originale = $this->obtenirImageEtInfosPourChemin($fichier_ou_dossier->getPathname());
$id = $this->convertirBaseNomFichierVersIdBdd($nom_fichier, $this->formats);
$id = $this->convertirBaseNomFichierVersIdBdd($nom_fichier, $this->formats);
 
// creation de miniatures pour chacuns des formats définis
// creation de miniatures pour chacuns des formats définis
foreach ($this->formats as $format) {
$this->creerEtStockerMiniatureFichierImageSelonFormat($id, $infos_image_originale, $format);
}
}
}
}
}
 
public function creerOuRenvoyerImage($id, $format) {
$dossier = $this->obtenirDossierPourFormat($id, $format);
$nom_fichier = $this->convertirIdBddVersNomFichier($id, $format);
$chemin_image = $dossier.'/'.$nom_fichier;
$chemin_image = $dossier.'/'.$nom_fichier;
 
$image = false;
if(!file_exists($chemin_image)) {
if (!file_exists($chemin_image)) {
$chemin_image_originale = $this->obtenirCheminImageOriginale($id);
$infos_image_originale = $this->obtenirImageEtInfosPourChemin($chemin_image_originale);
if($infos_image_originale) {
// le verrou est là dans le (rare) cas où l'image est déjà en train
// d'être générée par le script de création des miniatures ou bien
// d'être générée par le script de création des miniatures ou bien
// un autre instance de cette classe appelée par le web service
$fp = fopen($chemin_image_originale, "r");
// si le fichier est verrouillé, flock attendra qu'il se libère
// si le fichier est verrouillé, flock attendra qu'il se libère
$verrou = flock($fp, LOCK_EX);
if(!file_exists($chemin_image)) {
// si le fichier a été locké alors l'image était en train d'être générée
123,7 → 138,6
if ($format == 'O') {
// format original : rien à faire
$image_redimensionnee = $infos_image_originale['image'];
 
} else {
if ($this->estUnFormatRogne($format)) {
if ($this->mode == self::MODE_IMAGEMAGICK) {
144,7 → 158,6
$image_redimensionnee = $this->creerMiniature($infos_image_originale, $format);
}
}
 
return $image_redimensionnee;
}
 
152,7 → 165,7
* Déplace une image temporaire uploadée vers le répertoire de stockage d'images,
* en enregistrant les métadonnées et tout le tintouin.
* Si $conserverFichiersTemporaires vaut true, l'image est copiée et non déplacée.
*
*
* @param unknown $fichier
* @param unknown $id
* @param unknown $conserverFichiersTemporaires
160,24 → 173,24
*/
public function stockerFichierOriginal($fichier, $id, $conserverFichiersTemporaires=false) {
$chemin_fichier_origine = is_array($fichier) ? $fichier['tmp_name'] : $fichier;
 
$chemin_base_fichier = $this->creerSiNecessaireEtRenvoyerCheminStockageFichierPourIdEtFormat($id, 'O');
$nom_fichier = $this->convertirIdBddVersNomFichier($id, 'O');
 
$chemin_fichier = $chemin_base_fichier.'/'.$nom_fichier;
 
$deplacement_fichier = $this->stockerImageExterne($chemin_fichier_origine, $chemin_fichier, $conserverFichiersTemporaires);
 
if ($deplacement_fichier) {
$infos_image_originale = $this->obtenirImageEtInfosPourChemin($chemin_fichier);
$taux_compression = $this->renvoyerTauxCompressionPourPoids($infos_image_originale['poids_octets']);
 
if ($taux_compression < 100 && $this->mode == self::MODE_IMAGEMAGICK) {
$this->ecrireImageSurDisqueAvecMeta($chemin_fichier, $taux_compression);
}
 
return $infos_image_originale;
 
} else {
$erreur = 'ERROR : probleme durant le déplacement du fichier temporaire \n' ;
$this->logger('CEL_bugs',$erreur);
184,13 → 197,12
return false ;
}
}
 
public function stockerFichierEtCreerMiniatures($fichier, $id) {
$infos_image_originale_stockee = $this->stockerFichierOriginal($fichier, $id);
if($infos_image_originale_stockee) {
if ($infos_image_originale_stockee) {
$formats = $this->getFormats();
 
// creation de miniatures pour chacuns des formats définis
foreach($formats as $format) {
$this->creerEtStockerMiniatureFichierImageSelonFormat($id, $infos_image_originale_stockee, $format);
200,16 → 212,13
$this->logger('CEL_bugs',$erreur);
return false ;
}
return true ;
}
 
public function creerEtStockerMiniatureFichierImageSelonFormat($id ,$infos_image_originale, $format = 'O') {
$image_redimensionnee = $this->creerMiniatureImageSelonFormat($infos_image_originale, $format);
 
$taux_compression = $this->renvoyerTauxCompressionPourPoids($infos_image_originale['poids_octets']);
$this->ecrireImageSurDisque($image_redimensionnee, $id, $format, $taux_compression);
 
return true;
}
 
225,7 → 234,6
$infos_image_originale['largeur'],
$infos_image_originale['hauteur']
);
 
return $image_redimensionnee;
}
 
323,7 → 331,7
/**
* Déplace un fichier temporaire vers une destination donnée. Si
* $conserverFichiersTemporaires vaut true, le fichier est copié et non déplacé.
*
*
* @param unknown $chemin_fichier_temp
* @param unknown $chemin_destination
* @param string $conserverFichiersTemporaires
411,20 → 419,20
}
 
public function calculerTailleImage($informations_images, $taille_max) {
$HL_redimension = array();
$HL_redimension = array();
 
if ($this->estPaysage($informations_images)) {
$rapport = $informations_images['hauteur']/$informations_images['largeur'] ;
$HL_redimension['largeur'] = round($taille_max) ;
$HL_redimension['hauteur'] = round($taille_max*$rapport) ;
if ($this->estPaysage($informations_images)) {
$rapport = $informations_images['hauteur']/$informations_images['largeur'] ;
$HL_redimension['largeur'] = round($taille_max) ;
$HL_redimension['hauteur'] = round($taille_max*$rapport) ;
 
} else {
$rapport = $informations_images['largeur']/$informations_images['hauteur'] ;
$HL_redimension['hauteur'] = round($taille_max) ;
$HL_redimension['largeur'] = round($taille_max*$rapport) ;
}
} else {
$rapport = $informations_images['largeur']/$informations_images['hauteur'] ;
$HL_redimension['hauteur'] = round($taille_max) ;
$HL_redimension['largeur'] = round($taille_max*$rapport) ;
}
 
return $HL_redimension;
return $HL_redimension;
}
 
public function getFormats() {
452,11 → 460,11
 
$ratio_compression = 100 ;
 
if ($poids_octets >= $poids_max_octets) {
$ratio_compression = 75 ;
}
if ($poids_octets >= $poids_max_octets) {
$ratio_compression = 75 ;
}
 
return $ratio_compression;
return $ratio_compression;
}
 
public function convertirIdBddVersNomFichier($id, $format, $extension = 'jpg') {
472,10 → 480,9
public function convertirBaseNomFichierVersIdBdd($nom_fichier, $formats) {
$nom_fichier_sans_extension = trim($nom_fichier, '.jpg');
 
foreach($formats as $format) {
foreach ($formats as $format) {
$nom_fichier_sans_extension = trim($nom_fichier_sans_extension, '_'.$format);
}
 
$id_image = str_replace('_', '', $nom_fichier_sans_extension);
 
// suppression des 0 devant
503,7 → 510,7
$img = new Imagick($chemin_image_a_stocker);
 
// l'utilisation d'image magick préserve les métadonnées lors d'une recompression
$img->setformat("jpeg");
$img->setformat('jpeg');
$img->setImageCompression(imagick::COMPRESSION_JPEG);
$img->setCompressionQuality($compression);
$img->writeImage($chemin_image_a_stocker);
516,7 → 523,6
$image_blanche = imagecreatetruecolor($cote, $cote);
$blanc = imagecolorallocate($image_blanche, 255, 255, 255);
imagefilledrectangle($image_blanche, 0, 0, $cote, $cote, $blanc);
 
return $image_blanche;
}
 
526,7 → 532,7
 
/**
* Supprime une image du disque, ainsi que tous les formats générés
*
*
* @param Integer $id
* @return boolean true si tous les formats y compris l'original ont été détruits, false s'il en reste au moins un
*/
552,7 → 558,7
 
// recopie de Cel->logger() (pas d'extends pour ça)
public function logger($index,$chaine) {
if(!class_exists('Log')) {
if (!class_exists('Log')) {
Log::getInstance();
}
 
586,156 → 592,138
$largeur_vignette = $dimension_vignettes['largeur'];
$hauteur_vignette = $dimension_vignettes['hauteur'];
 
// source dimensions
$largeur_image_originale = $informations_image['largeur'];
$hauteur_image_originale = $informations_image['hauteur'];
// source dimensions
$largeur_image_originale = $informations_image['largeur'];
$hauteur_image_originale = $informations_image['hauteur'];
 
$chemin_image = $informations_image['chemin'];
$chemin_image = $informations_image['chemin'];
 
//if ($largeur_vignette > $largeur_image_originale || $hauteur_vignette > $hauteur_image_originale)
// die("Target dimensions must be smaller or equal to source dimensions.");
// parameters for the edge-maximizing crop algorithm
$r = 1; // radius of edge filter
$nk = 9; // scale count: number of crop sizes to try
$gamma = 0.2; // edge normalization parameter -- see documentation
$ar = $largeur_vignette/$hauteur_vignette; // target aspect ratio (AR)
$ar0 = $largeur_image_originale/$hauteur_image_originale; // original aspect ratio (AR)
 
// parameters for the edge-maximizing crop algorithm
$r = 1; // radius of edge filter
$nk = 9; // scale count: number of crop sizes to try
$gamma = 0.2; // edge normalization parameter -- see documentation
$ar = $largeur_vignette/$hauteur_vignette; // target aspect ratio (AR)
$ar0 = $largeur_image_originale/$hauteur_image_originale; // original aspect ratio (AR)
//echo("$chemin_image: $largeur_image_originale x $hauteur_image_originale => $largeur_vignette x $hauteur_vignette");
$img = new Imagick($chemin_image);
$imgcp = clone $img;
 
//echo("$chemin_image: $largeur_image_originale x $hauteur_image_originale => $largeur_vignette x $hauteur_vignette");
$img = new Imagick($chemin_image);
$imgcp = clone $img;
// compute center of edginess
$img->edgeImage($r);
$img->modulateImage(100,0,100); // grayscale
$img->blackThresholdImage("#0f0f0f");
$retour_ecriture_img = $img->writeImage($out);
 
// compute center of edginess
$img->edgeImage($r);
$img->modulateImage(100,0,100); // grayscale
$img->blackThresholdImage("#0f0f0f");
$retour_ecriture_img = $img->writeImage($out);
if ($retour_ecriture_img !== true) {
error_log("Erreur d'écriture Imagick : [" . $chemin_image . "] vers [" . $out . "]");
$erreur_ecriture = true;
}
// use gd for random pixel access
$im = ImageCreateFromJpeg($out);
 
if ($retour_ecriture_img !== true) {
error_log("Erreur d'écriture Imagick : [" . $chemin_image . "] vers [" . $out . "]");
$erreur_ecriture = true;
}
// use gd for random pixel access
$im = ImageCreateFromJpeg($out);
if ($im === false) {
error_log("GD ne peut pas lire l'image créée par Imagick : [" . $chemin_image . "] vers [" . $out . "]");
$erreur_ecriture = true;
}
 
if ($im === false) {
error_log("GD ne peut pas lire l'image créée par Imagick : [" . $chemin_image . "] vers [" . $out . "]");
$erreur_ecriture = true;
}
if (! $erreur_ecriture) {
$xcenter = 0;
$ycenter = 0;
$sum = 0;
$n = 100000;
for ($k=0; $k<$n; $k++) {
$i = mt_rand(0,$largeur_image_originale-1);
$j = mt_rand(0,$hauteur_image_originale-1);
$val = imagecolorat($im, $i, $j) & 0xFF;
$sum += $val;
$xcenter += ($i+1)*$val;
$ycenter += ($j+1)*$val;
}
$xcenter /= $sum;
$ycenter /= $sum;
// crop source img to target AR
if ($largeur_image_originale/$hauteur_image_originale > $ar) {
// source AR wider than target
// crop width to target AR
$wcrop0 = round($ar*$hauteur_image_originale);
$hcrop0 = $hauteur_image_originale;
} else {
// crop height to target AR
$wcrop0 = $largeur_image_originale;
$hcrop0 = round($largeur_image_originale/$ar);
}
// crop parameters for all scales and translations
$params = array();
// crop at different scales
$hgap = $hcrop0 - $hauteur_vignette;
$hinc = ($nk == 1) ? 0 : $hgap / ($nk - 1);
$wgap = $wcrop0 - $largeur_vignette;
$winc = ($nk == 1) ? 0 : $wgap / ($nk - 1);
// find window with highest normalized edginess
$n = 10000;
$maxbetanorm = 0;
$maxfile = '';
$maxparam = array('w'=>0, 'h'=>0, 'x'=>0, 'y'=>0);
for ($k = 0; $k < $nk; $k++) {
$hcrop = round($hcrop0 - $k*$hinc);
$wcrop = round($wcrop0 - $k*$winc);
$xcrop = $xcenter - $wcrop / 2;
$ycrop = $ycenter - $hcrop / 2;
//echo("crop: $wcrop, $hcrop, $xcrop, $ycrop");
if ($xcrop < 0) $xcrop = 0;
if ($xcrop+$wcrop > $largeur_image_originale) $xcrop = $largeur_image_originale-$wcrop;
if ($ycrop < 0) $ycrop = 0;
if ($ycrop+$hcrop > $hauteur_image_originale) $ycrop = $hauteur_image_originale-$hcrop;
/*if (self::MODE_DEBUG) {
// debug
$currfile = '/home/aurelien/web/file_tmp/'."image$k.jpg";
$currimg = clone $img;
$c= new ImagickDraw();
$c->setFillColor("red");
$c->circle($xcenter, $ycenter, $xcenter, $ycenter+4);
$currimg->drawImage($c);
$currimg->cropImage($wcrop, $hcrop, $xcrop, $ycrop);
$currimg->writeImage($currfile);
$currimg->destroy();
}*/
$beta = 0;
for ($c=0; $c<$n; $c++) {
$i = mt_rand(0,$wcrop-1);
$j = mt_rand(0,$hcrop-1);
$beta += imagecolorat($im, $xcrop+$i, $ycrop+$j) & 0xFF;
}
$area = $wcrop * $hcrop;
$betanorm = $beta / ($n*pow($area, $gamma-1));
// echo("beta: $beta; betan: $betanorm");
// echo("image$k.jpg:<br/>\n<img src=\"$currfile\"/>");
// best image found, save it
if ($betanorm > $maxbetanorm) {
$maxbetanorm = $betanorm;
$maxparam['w'] = $wcrop;
$maxparam['h'] = $hcrop;
$maxparam['x'] = $xcrop;
$maxparam['y'] = $ycrop;
// $maxfile = $currfile;
}
}
// écrasement de l'image par la version "croppée"
$imgcp->cropImage($maxparam['w'], $maxparam['h'], $maxparam['x'], $maxparam['y']);
$imgcp->scaleImage($largeur_vignette, $hauteur_vignette);
$imgcp->writeImage($out);
if (! $erreur_ecriture) {
$xcenter = 0;
$ycenter = 0;
$sum = 0;
$n = 100000;
for ($k=0; $k<$n; $k++) {
$i = mt_rand(0,$largeur_image_originale-1);
$j = mt_rand(0,$hauteur_image_originale-1);
$val = imagecolorat($im, $i, $j) & 0xFF;
$sum += $val;
$xcenter += ($i+1)*$val;
$ycenter += ($j+1)*$val;
}
$xcenter /= $sum;
$ycenter /= $sum;
 
// return image
chmod($out, 0777);
$img->destroy();
$imgcp->destroy();
$image_sortie = ImageCreateFromJpeg($out);
} else {
// image n'a pas pu être croppée - on retourne l'originale
//$image_sortie = ImageCreateFromJpeg($chemin_image);
$image_sortie = false;
}
// crop source img to target AR
if ($largeur_image_originale/$hauteur_image_originale > $ar) {
// source AR wider than target
// crop width to target AR
$wcrop0 = round($ar*$hauteur_image_originale);
$hcrop0 = $hauteur_image_originale;
} else {
// crop height to target AR
$wcrop0 = $largeur_image_originale;
$hcrop0 = round($largeur_image_originale/$ar);
}
 
// destruction fichier temporaire dans tous les cas
unlink($out);
// crop parameters for all scales and translations
$params = array();
 
return $image_sortie;
// crop at different scales
$hgap = $hcrop0 - $hauteur_vignette;
$hinc = ($nk == 1) ? 0 : $hgap / ($nk - 1);
$wgap = $wcrop0 - $largeur_vignette;
$winc = ($nk == 1) ? 0 : $wgap / ($nk - 1);
 
// find window with highest normalized edginess
$n = 10000;
$maxbetanorm = 0;
$maxfile = '';
$maxparam = array('w'=>0, 'h'=>0, 'x'=>0, 'y'=>0);
 
for ($k = 0; $k < $nk; $k++) {
$hcrop = round($hcrop0 - $k*$hinc);
$wcrop = round($wcrop0 - $k*$winc);
$xcrop = $xcenter - $wcrop / 2;
$ycrop = $ycenter - $hcrop / 2;
//echo("crop: $wcrop, $hcrop, $xcrop, $ycrop");
 
if ($xcrop < 0) $xcrop = 0;
if ($xcrop+$wcrop > $largeur_image_originale) $xcrop = $largeur_image_originale-$wcrop;
if ($ycrop < 0) $ycrop = 0;
if ($ycrop+$hcrop > $hauteur_image_originale) $ycrop = $hauteur_image_originale-$hcrop;
 
$beta = 0;
for ($c=0; $c<$n; $c++) {
$i = mt_rand(0,$wcrop-1);
$j = mt_rand(0,$hcrop-1);
$beta += imagecolorat($im, $xcrop+$i, $ycrop+$j) & 0xFF;
}
$area = $wcrop * $hcrop;
$betanorm = $beta / ($n*pow($area, $gamma-1));
// echo("beta: $beta; betan: $betanorm");
// echo("image$k.jpg:<br/>\n<img src=\"$currfile\"/>");
// best image found, save it
 
if ($betanorm > $maxbetanorm) {
 
$maxbetanorm = $betanorm;
$maxparam['w'] = $wcrop;
$maxparam['h'] = $hcrop;
$maxparam['x'] = $xcrop;
$maxparam['y'] = $ycrop;
// $maxfile = $currfile;
}
}
 
// écrasement de l'image par la version "croppée"
$imgcp->cropImage($maxparam['w'], $maxparam['h'], $maxparam['x'], $maxparam['y']);
$imgcp->scaleImage($largeur_vignette, $hauteur_vignette);
$imgcp->writeImage($out);
 
// return image
chmod($out, 0777);
$img->destroy();
$imgcp->destroy();
$image_sortie = ImageCreateFromJpeg($out);
} else {
// image n'a pas pu être croppée - on retourne l'originale
//$image_sortie = ImageCreateFromJpeg($chemin_image);
$image_sortie = false;
}
 
// destruction fichier temporaire dans tous les cas
unlink($out);
 
return $image_sortie;
}
}
?>
}