Results 1 to 2 of 2

Thread: Make thumbed images with fit to box aspect ration fucntion

  1. #1
    Join Date
    May 2004
    Posts
    530
    Rep Power
    0

    Default Make thumbed images with fit to box aspect ration fucntion

    I am working on a project in which i need to make thumbed images and maintain aspect ratio based on a set width and height. After searching the web i found examples that only helped me for one or the other need . So i combined both fucntionality into one, here is my function(this uses GD library to manipulate images):

    Code:
    function make_thumb($src, $thumbdirectory,$thumbedfile, $desired_width,$desired_height) {
    
      /* read the source image */
      
      $source_image = imagecreatefromjpeg($src);
      $width = imagesx($source_image);
      $height = imagesy($source_image);
      
     
      //calculate aspect ratio
       if ($width > $height) {
        $percentage = ($desired_width / $width);
       } else {
         $percentage = ($desired_height / $height);
       }
    
       $desired_width = round($width * $percentage);
       $desired_height = round($height * $percentage);
      
      /* create a new, "virtual" image */
      $virtual_image = imagecreatetruecolor($desired_width, $desired_height);
      
      /* copy source image at a resized size */
      imagecopyresampled($virtual_image, $source_image, 0, 0, 0, 0, $desired_width, $desired_height, $width, $height);
      
      //chk if destination exist and make it if not
      if(!is_dir($thumbdirectory)){
        mkdir($thumbdirectory, 0755);
    	chmod($thumbdirectory, 0755);
      
       /* create the physical thumbnail image to its destination */
        imagejpeg($virtual_image, $thumbedfile);
      
      }  else {
    	chmod($thumbdirectory, 0755);
    	   
    	   
      
         /* create the physical thumbnail image to its destination */
        imagejpeg($virtual_image, $thumbedfile);
    	
    	
    	}
    	
    	
    	
    }
    Last edited by leocrawf; Sep 8, 2012 at 10:03 AM.
    "...men are that they might have joy."
    Nephi

  2. #2
    Join Date
    Feb 2003
    Posts
    3,184
    Rep Power
    0

    Default

    Cool, very elegant.

    Only difference in mine is this;
    Code:
    if(is_resource(@imageCreateTrueColor(100,100))) { //check gd library version
    	$desImg = imageCreateTrueColor($thumbWidth,$thumbHeight);
    	imageCopyResampled($desImg, $srcImg, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $srcWidth, $srcHeight);
    	} else {
    		//version < 2.0
    		$desImg = imageCreate($thumbWidth,$thumbHeight);
    		imageCopyResized($desImg, $srcImg, 0, 0, $srcX, $srcY, $thumbWidth, $thumbHeight, $thumbWidth, $thumbHeight);
    	}
    Which probably is pointless since everybody has upgraded servers now.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •