8796 sujets

Développement web côté serveur, CMS

Voici un script que j'ai en parti modifié, c'est un album photo.

Cet album va chercher les images dans le répertoire courant
mais je n'arrive pas à faire en sorte qu'il aille chercher les
image dans un sous-répertoire.

J'ai essayé là ou sont les :
opendir
dirname
et la création des image par gd


$directory = '/uploaded/';

J'aimerais que $directory soit au bon endroit. Quelqu'un peut
m'aider à résoudre ce problème?

 <?php

$columns     = 5;
$thmb_width  = 100;
$thmb_height = 90;

function resizeImage($originalImage,$toWidth,$toHeight){
    
    // Get the original geometry and calculate scales
    list($width, $height) = getimagesize($originalImage);
    $xscale=$width/$toWidth;
    $yscale=$height/$toHeight;
    
    // Recalculate new size with default ratio
    if ($yscale>$xscale){
        $new_width = round($width * (1/$yscale));
        $new_height = round($height * (1/$yscale));
    }
    else {
        $new_width = round($width * (1/$xscale));
        $new_height = round($height * (1/$xscale));
    }
    // Resize the original image
    $imageResized = imagecreatetruecolor($new_width, $new_height);
    $imageTmp     = imagecreatefromjpeg ($originalImage);
    imagecopyresampled($imageResized, $imageTmp, 0, 0, 0, 0, 
                       $new_width, $new_height, $width, $height);

    return $imageResized;
} 

function generateThumbnails(){
    global $thmb_width,$thmb_height;
    
    // Open the actual directory
    if ($handle = opendir(".")) {
        // Read all file from the actual directory
        while ($file = readdir($handle))  {
            // Check whether tha actual item is a valid file
            if (is_file($file)){
                // Check whether the actual image is a thumbnail
                  if (strpos($file,'_th.jpg')){
                      $isThumb = true;
                  }
                  else {
                      $isThumb = false;
                  }
              
                  if (!$isThumb) {
                  // Process the file string
                  $dirName  = substr($file,0,strpos($file,basename($file)));
                  if (strlen($dirName) < 1) $dirName = '.';
                  $fileName = basename($file);
                  $fileMain = substr($fileName,0,strrpos($fileName,'.'));
                  $extName  = substr($fileName,strrpos($fileName,'.'),
                                      strlen($fileName)-strrpos($fileName,'.'));
                      
											// Check if the actual file is a jpeg image
											if (($extName == '.jpg') || ($extName == '.jpeg')){
												$thmbFile = $dirName.'/'.$fileMain.'_th.jpg';
													// If a thumbnail dosn't exists tahn create a new one
													if (!file_exists($thmbFile)){
															imagejpeg(resizeImage($file,$thmb_width,$thmb_height)
																			 ,$thmbFile,80);
													}
											}
                  } 
             }
        }
    }
}

function getNormalImage($file){
    $base = substr($file,0,strrpos($file,'_th.jpg'));
    if (file_exists($base.'.jpg')) return $base.'.jpg';
    elseif (file_exists($base.'.jpeg')) return $base.'.jpeg';
    else return "";
}

function displayPhotos(){
  global $columns;
  
  generateThumbnails();
  $act = 0;
  // Open the actual directory
		if ($handle = opendir(".")) {
				// Read all file from the actual directory
				while ($file = readdir($handle))  {
						// Check whether tha actual item is a valid file
					if (is_file($file)){
							// Check whether the actual image is a thumbnail
								if (strpos($file,'_th.jpg')){
									++$act;
										if ($act > $columns) {
												echo '</tr><tr>
													 <td class="photo"><a href="'.getNormalImage($file).'">
															 <img src="'.$file.'" alt="'.$file.'"/></a></td>';    
												$act = 1;
										}
										else {
										
												$sourcear = str_replace("_th","",getNormalImage($file));
												$source = imagecreatefromjpeg($sourcear); // La photo est la source
												$destination = imagecreatetruecolor(640, 480); // On crée la miniature vide
												$largeur_source = imagesx($source);
												$hauteur_source = imagesy($source);
												$largeur_destination = imagesx($destination);
												$hauteur_destination = imagesy($destination);
												imagecopyresampled($destination, $source, 0, 0, 0, 0, $largeur_destination, $hauteur_destination, $largeur_source, $hauteur_source);
												imagejpeg($destination, getNormalImage($file));

												$description = str_replace("_th.jpg","",$file);
												echo '<td class="photo"><a href="'.getNormalImage($file).'" onclick="return popitup(\''.getNormalImage($file).'\')">
													 <img src="'.$file.'" alt="'.$file.'"/></a><br /><div style="font-size:9px;font-family:Verdana;color:DarkRed;text-align:center;">'.$description.'</div></td>';    
										}
								}
						}
				}
		}    
}

?>

Modifié par dan4 (13 Feb 2011 - 15:23)
salut

c'est de récursivité dont tu as besoin Smiley cligne .
une source à lire avec un code bien plus actuel que celui-là et fait une recherche sur le forum avec recursivedirectoryiterator, j'ai publié une classe il y à quelque semaine pour scanner des dossiers avec filtrage possible.
Merci keran, je vais regarder les nouvelles possibilités que je ne connaissait pas.

J'ai complètement refais mon album et fais un uploader avec le redimensionnement à l'intérieur.

Mon seul hic, c'est que j'ai dû placer deux comme ceci pour redimensionner les images originales et un pour les miniature.


1er :
            $source_pic = $dossier.$fichier;
            $destination_pic = $dossier.$fichier;

            $max_width = $largeur;
            $max_height = $hauteur;

            $src = imagecreatefromjpeg($source_pic);
            list($width,$height)=getimagesize($source_pic);

            $x_ratio = $max_width / $width;
            $y_ratio = $max_height / $height;

            if( ($width <= $max_width) && ($height <= $max_height) ){
                $tn_width = $width;
                $tn_height = $height;
                }
                elseif (($x_ratio * $height) < $max_height){
                    $tn_height = ceil($x_ratio * $height);
                    $tn_width = $max_width;
                }
                else{
                    $tn_width = ceil($y_ratio * $width);
                    $tn_height = $max_height;
                }

            $tmp=imagecreatetruecolor($tn_width,$tn_height);
            imagecopyresampled($tmp,$src,0,0,0,0,$tn_width, $tn_height,$width,$height);

            imagejpeg($tmp,$destination_pic,$resolution);
            imagedestroy($src);
            imagedestroy($tmp);
            
2e:        // thumbfiles
                  
            $source_pic = $dossier.$fichier;
            $destination_pic = $dossier.$fichier;
            
            $destination_pic = str_replace(".jpg","_th.jpg",$destination_pic);
            
            $max_width = $largeur_t;
            $max_height = $hauteur_t;

            $src = imagecreatefromjpeg($source_pic);
            list($width,$height)=getimagesize($source_pic);

            $x_ratio = $max_width / $width;
            $y_ratio = $max_height / $height;

            if( ($width <= $max_width) && ($height <= $max_height) ){
                $tn_width = $width;
                $tn_height = $height;
                }
                elseif (($x_ratio * $height) < $max_height){
                    $tn_height = ceil($x_ratio * $height);
                    $tn_width = $max_width;
                }
                else{
                    $tn_width = ceil($y_ratio * $width);
                    $tn_height = $max_height;
                }

            $tmp=imagecreatetruecolor($tn_width,$tn_height);
            imagecopyresampled($tmp,$src,0,0,0,0,$tn_width, $tn_height,$width,$height);
           
            imagejpeg($tmp,$destination_pic,$resolution);
            imagedestroy($src);
            imagedestroy($tmp);
            


Je ne sais pas si y aurait moyen de faire plus concis, plus léger.
Modifié par dan4 (15 Feb 2011 - 03:15)
salut

Tu peux faire plus concis en concevant une méthode pour les fonctions de redimensionnement et en lui passant comme paramètres chemin pour les images, dossier d'enregistrement, etc. Du genre :


function miniatures($ch,$ratio = 120) {
	$imgSrc = imagecreatefromjpeg($ch);
	$largeurSrc = imagesx($imgSrc);
	$hauteurSrc = imagesy($imgSrc);
	if ($largeurSrc >= $hauteurSrc) { 
		$pourcentage = ($ratio / $largeurSrc); 
	} else { 
		$pourcentage = ($ratio / $hauteurSrc);
	}
	$largeur = round($largeurSrc * $pourcentage); 
	$hauteur = round($hauteurSrc * $pourcentage);
	$l = $largeur;
	$h = $hauteur;
	$lSrc = $largeurSrc;
	$hSrc = $hauteurSrc;
	$mini = ImageCreateTrueColor($l, $h);
	ImageCopyResampled($mini, $imgSrc, 0, 0, 0, 0, $l, $h, $lSrc, $hSrc);
	//header('Content-type: image/jpeg');
	imagejpeg($mini,'mini/'.$ch,100);
	imagedestroy($mini);
}

miniatures($image);


c'est la base, après tu bricoles comme tu veux, en rajoutant par exemple, des messages d'erreurs possibles. A noter, cette mèthode n'utilise aucun retour. Je m'en sert pour un projet complet, ici, c'est juste pour l'exemple. une autre bien plus complète, à ne pas utiliser tel que, elle fait partout elle aussi d'un tout, mais il suffit de modifier les chemins définis ici par des constantes, je te laisse faire, si tu veux tester évidement. C'est du code fonctionnel et testé que j'utilise tout le temps sur tout les projets.



private function redimensionne($image) {
		if(extension_loaded('gd')) {
   	   		$max = 512;
			$info = pathinfo ($image);
			$extension = strtolower ($info ['extension']);
			switch ($extension) {
				case 'jpg' :
				case 'jpeg' :
					$imgSrc = imagecreatefromjpeg(Chemin::REDIM.$image);
					break;
				case 'png' :
					$imgSrc = imagecreatefrompng(Chemin::REDIM.$image);
					break;
				case 'gif' :
					$imgSrc = imagecreatefromgif(Chemin::REDIM.$image);
					break;
				default :
					unset($imgSrc);
			}
		
			$largeurSrc = imagesx($imgSrc);
			$hauteurSrc = imagesy($imgSrc);
			if ($largeurSrc > $max) {
				$pourcentage = ($max / $largeurSrc);
			} else {
				$pourcentage = ($max / $hauteurSrc);
			}
			$largeur = round($largeurSrc * $pourcentage);
			$hauteur = round($hauteurSrc * $pourcentage);
			$l = $largeur;
			$h = $hauteur;
			$lSrc = $largeurSrc;
			$hSrc = $hauteurSrc;
			$mini = ImageCreateTrueColor($l, $h);
			ImageCopyResampled($mini, $imgSrc, 0, 0, 0, 0, $l, $h, $lSrc, $hSrc);
			switch ($extension) {
				case 'jpg' :
				case 'jpeg' :
					imagejpeg($mini, Chemin::DIAPO.$image);
					unlink(Chemin::REDIM.$image);
					break;
				case 'gif' :
					imagegif($mini, Chemin::DIAPO.$image);
					unlink (Chemin::REDIM . $image);
					break;
				case 'png' :
					imagepng($mini, Chemin::DIAPO.$image);
					unlink(Chemin::REDIM.$image);
					break;
			}
			imagedestroy($mini);
		}
	}