This niftly little function I wrote uses [man]getimagesize/man to create a nice little thumbnail of an image while keeping the aspect ratio. It does not store the new image, but merely sets the dimensions for the <img> tag. Any suggestions or concerns with this code?

function imageresize($max_width,$max_height,$image){

$dimensions=getimagesize($image);

$width_percentage=$max_width/$dimensions[0];
$height_percentage=$max_height/$dimensions[1];

if($width_percentage <= $height_percentage){
	$new_width=$width_percentage*$dimensions[0];
	$new_height=$width_percentage*$dimensions[1];
}else{
	$new_width=$height_percentage*$dimensions[0];
	$new_height=$height_percentage*$dimensions[1];
}

$new_image=array($new_width,$new_height);
return $new_image;
}

$dimensions=imageresize("100","250","images/blog.gif");

$image="<img src='images/blog.gif' width='$dimensions[0]' height='$dimensions[1]'>";

?>

    I'd use round() or similar so that nonintegral sizes don't get used.

    But then, I don't like making "thumbnails" out of full-sized images by just using smaller image dimensions. There's no saving for anyone anywhere except screen real estate.

      Thank you, I will impliment the [man]round/man.

      Originally I looked at creating a whole new image and storing it, but that was a little over my head, so I went with the latter for simplicity's sake.

        Originally posted by ThaSpY
        Thank you, I will impliment the [man]round/man.

        Originally I looked at creating a whole new image and storing it, but that was a little over my head, so I went with the latter for simplicity's sake.

        It's actually surprisingly simple [man]imagecreatefromjpeg[/man] [man]imagecreatetruecolor[/man] [man]imagecopyresized[/man] [man]imagejpeg[/man] [man]imagedestroy[/man] or something like that.. and say you want to make the thumbnails greyscale, Weedpacket posted a nice little example here: http://www.phpbuilder.com/board/showthread.php?postid=10479545#post10479545

          19 days later

          Try this one, it creates the thumbs and saves them to a file. Resizing the image in the img tag is a bad idea and you really should create a seperate thumb image. Keep in mind that when using this to resize multiple images, runtime can be rather lengthy since the image functions seem to be very resource intensive

          <?php
          /*
          mkthumb() function.  05/15/2004
          
          Parameters:
          	$dirname - Path of the source photo.
          	$filename - Filename of source photo, which will also be used to create the thumb.
          	$thumbdir - Path to save the thumb to. Must be different than $dirname.
          	$thumb_size - Desired size of the longest side of the thumb in pixels. Default is 120.
          
          ex:
          	$img_path = '../img_path';
          	$img_name = 'img.jpg';
          	$thumb_path = '../thumb_path';
          	$size = 100;
          
          mkthumb($img_path, $img_name, $thumb_path, $size);
          */
          
          function mkthumb($dirname, $filename, $thumbdir, $thumb_size = 120)
          {
          	if (isset($filename))
          	{
          		//get filetype and check to make sure it is an accepable image. if gif, jpeg, or png create
          		//source image.
          		$imtype = exif_imagetype($dirname.$filename);
          
          	switch($imtype)
          	{
          		case 1 : //Image is type gif.
          			$im = imagecreatefromgif($dirname.$filename);
          			break;
          		case 2 : //Image is type jpeg.
          			$im = imagecreatefromjpeg($dirname.$filename);
          			break;
          		case 3 : //Image is png.
          			$im = imagecreatefrompng($dirname.$filename);
          			break;
          		default : //File not accepted.
          			echo "Error: $filename is an invalid file.<br>";
          			break;
          	}
          
          	if (isset($im)) 
          	{
          		//get width of source photo.
          		$width = ImageSX($im);
          		$height = ImageSY($im);
          
          		//set aspect ratio so that the thumb is not distorted.
          		if ($width < $height)
          		{
          			$asp_ratio = $thumb_size/$height;
          		}
          		else
          		{
          			$asp_ratio = $thumb_size/$width;
          		}
          
          		//calculate thumb width using aspect ratio percetage.
          		$thumb_width = round(($width * $asp_ratio));
          		$thumb_height = round(($height * $asp_ratio));
          
          		//create thumb image.
          		$im_thumb = imagecreatetruecolor($thumb_width, $thumb_height);
          
          		//resize and copy source image to the thumb image.
          		imagecopyresampled($im_thumb, $im, 0, 0, 0, 0, $thumb_width, $thumb_height, $width,$height);
          
          		//create 
          		switch($imtype)
          		{
          			case 1 : //Image is type gif.
          				$im_new = imagegif($im_thumb,$thumbdir.$filename);
          				break;
          			case 2 : //Image is type jpeg.
          				$im_new = imagejpeg($im_thumb,$thumbdir.$filename);
          				break;
          			case 3 : //Image is png.
          				$im_new = imagepng($im_thumb,$thumbdir.$filename);
          				break;
          			default :
          				$im_new = imagejpeg($im_thumb,$thumbdir.$filename);
          				break;
          		}	
          		imagedestroy($im);
          		imagedestroy($im_thumb);
          	}
          	else
          	{
          		echo "Error: Cannot process image<br>";
          		return false;
          	}
          }
          else
          {
          	echo "Error: Filename required<br>";
          	return false;
          }
          echo "Created thumb $thumbdir$filename<br>";
          return true;
          }
          
          ?>
          

            Note that, that will not work with GIF's if the person is using GD 1.6 or later.

              24 days later

              Not sure were i took this from but i love it!

              I use it to resize Images without saving them, also good for showing thmubnails of big image.

              also will keep aspect,
              use it in your IMG SRC tag
              like so
              <IMG SRC="tn_image.php?image=file.jpg">

              <?php
              // make thmubnail of image
              function sizeImage($image, $x, $y, $proportional) {
              if (!$attr = getimagesize($image)) {
              trigger_error("GD: Image does not exist. Must be gif, jpeg, or png!",E_USER_ERROR);
              }
              
              switch ($attr[2]) {
              case 1:
              $image = imagecreatefromgif($image);
              break;
              case 2:
              $image = imagecreatefromjpeg($image);
              break;
              case 3:
              $image = imagecreatefrompng($image);
              break;
              default:
              trigger_error("GD: Image type wrong. Must be gif, jpeg, or png!", E_USER_ERROR);
              }
              if ($proportional) {
              if ($attr[0]<$attr[1]){
              $x = $y * ($attr[0]/$attr[1]);
              }
              else{
              $y = $x / ($attr[0]/$attr[1]);
              } 
              }
              $newimage = imagecreatetruecolor($x,$y);
              imagecopyresampled($newimage, $image, 0, 0, 0, 0, $x, $y, $attr[0], $attr[1]);
              imagepng($newimage);
              imagedestroy($image);
              imagedestroy($newimage);
              }
              $image = $_GET['image']; //image location
              $x = 150; //width
              $y = 100; //height
              $proportional = TRUE; //proportional or not
              header("Content-type: image/png"); //so we can use the image right in a tag. <img src="image.php?image=me.gif">
              sizeImage($image, $x, $y, $proportional);
              ?>
                7 days later

                Hello guys. I´ve downloaded this code from the site but can´t work out why does it make so dirty thumbnails. They are coloured, or just bad. I´ll show you an example if you want. Well, the code is:

                <?$maxw = 150; // maximum width of images (height will be scaled accordingly)
                $thumbdir = "thumbs"; // directory to place thumbnail images
                $url = $_SERVER["PHP_SELF"]."?";
                $sfxs = array(".jpg",".jpeg",".png",".JPG");
                $curdir = dirname(stripslashes($_SERVER["PATH_TRANSLATED"]));
                $slash = (strstr($curdir,"\\") ) ? "\\" : "/";
                $thumbdir = $thumbdir;
                $images = array();
                @ $handle = opendir($curdir);
                if (!$handle ) {
                	error("could not open directory!");
                	exit;
                }
                
                while ( $file = readdir($handle) ) {
                	if (isValid($file,$sfxs) ) {
                		$tmp = array();
                		$tmp[0] = $file;
                		$tmp[1] = filemtime($file);
                		$tmp[2] = filesize($file);
                		array_push($images,$tmp);
                		// do we need to create a thumbnail?
                		if ( !file_exists($thumbdir.$slash.$file) ) {
                			createThumb($file);
                		}
                	}
                }
                
                function isValid($f,$a) {
                	$t = getSuffix($f);
                	return ( in_array($t,$a) ) ? true : false;
                }
                function getSuffix($f) {
                	$n = strrpos($f,".");
                	return substr($f,$n,strlen($f)-$n);
                }
                function createThumb($f) {
                	// use max width config value
                	global $maxw, $curdir, $copyfile, $thumbdir, $slash;
                	$type = getSuffix($f);
                	// png or jpeg?
                	// either way get image
                	if ($type==".png") {
                		$input = imagecreatefrompng($f);
                	} else {
                		$input = imagecreatefromjpeg($f);
                	}
                	if ( !$input ) {
                		error("not a valid image file :(");
                		return false;
                	}
                	// get size ( [0]=width, [1]=height )
                	$tmp = getimagesize($f);
                	if ( !$tmp ) {
                		error("Could not get input image size");
                		return false;
                	}
                	// get width of new thumbnail by taking
                	// the smaller value from max and tmp width
                	$w = ($tmp[0]>$maxw) ? $maxw : $tmp[0];
                	// scale height according to width
                	$h = $tmp[1] * ($maxw/$tmp[0]);
                	// create output image
                	@ $output = imagecreate($w,$h);
                	if ( !$output ) {
                		error("could not create output image");
                		return false;
                	}
                	// copy big image over to thumbnail, and resize down
                	imagecopyresampled( $output,$input, 0,0, 0,0, $w,$h, $tmp[0],$tmp[1] );
                	$newfile = $thumbdir.$slash.$f;
                	// do the outputting!
                	if ( $type == ".png" ) {
                		imagepng($output,$newfile);
                	} else {
                		imagejpeg($output,$newfile);
                	}
                }
                function error($str) {
                	echo '<div style="background-color:#ffffff;color:#660000;font-weight:bold">'.$str.'</div>';
                }
                ?>

                Any ideas? Thanks in advance!

                Edit: changed resized to resampled.

                  use imagecopyresampled() instead of imagecopyresized().

                    It didn´t work, BuzzLY. Thanks anyway. 🙂

                      Post your original and thumbnail images. And what do you mean "it didn't work?" The command doesn't work, or it didn't help the quality?

                      Try using imagecreatetruecolor() instead of imagecreate().

                        Sorry, by didn´t work I meant it didn´t change anything! So the images keep doing that, I´ll show you:
                        or

                        I didn´t change to imagecreatetruecolor yet, anyway I don´t use pngs.

                        If it helps you can test in http://roscorgal.com.ar/test/users/, where you can upload images and it resizes it and shows the small image.

                        Thanks again!

                          imagecreate() creates a palette-based image. You need to use imagecreatetruecolor(). Replace this line:

                          [FONT=courier new]@ $output = imagecreate($w,$h);[/FONT]

                          with this:

                          [FONT=courier new]@ $output = imagecreatetruecolor($w,$h);[/FONT]

                            Originally posted by BuzzLY
                            imagecreate() creates a palette-based image. You need to use imagecreatetruecolor(). Replace this line:

                            [FONT=courier new]@ $output = imagecreate($w,$h);[/FONT]

                            with this:

                            [FONT=courier new]@ $output = imagecreatetruecolor($w,$h);[/FONT]

                            It was EXACTLY that. Thanks a lot, BuzzLY! Now everything works fine. So, solved.

                            If I thought it didn´t work it was because it showed my caché files instead of the new ones.

                              Write a Reply...