First, lets take a look on what problem will this tutorial solve, so you can decide if you want to read more :)

We will write 2 functions for creating thumbnails from random image (png, jpg, gif). First function will take thumbnail width and height set by you, and cut the “most important” part from the image (I’m assuming, that you are creating thumbnails of websites, so center top is the area I’m talking about) according to thumbnail ratio, and resize it into your thumbnail in exact size that you’ve set. Second function will take max thumbnail width and height set by you, and resize the image so it will fit your max values, but with preserving its original resolution ratio.

1.) Generate thumbnail of exact size

This function will cut the biggest possible top center of image, so it can be resized into width and height you need without deforming it. The advantage of this method is, taht all thumbnails have same resolution, therefore they can be easily styled on website, and it just looks better. Disadvantage is, that sometimes, it could cut the important part of image.
For better understanding, click on the image below.

thumb-cut-explanation

Lets define the function:

create_thumb( string $source_path, string $destination_path, int $thumb_width, int $thumb_height [, int $quality [, int $overwrite]] )

Parameters:

  • $source_path: Path to source image (jpg, jpeg, png, gif).
  • $destination_path: Thumbnail destination path. It has to have *.jpg extension, as all thumbnails will be generated in jpg.
  • $thumb_width: Final thumbnail width.
  • $thumb_height: Final thumbnail height.
  • $quality: JPG compression quality (bigger: better quality,larger file). Range 0-100 (optimal 85).
  • $overwrite: Set as true if you wan this function to overwrite thumbnail if it already exists.

Lets start with code. I’m lazy to comment every line, so I’ll just paste the whole function with comments in code :) Also, I was asked about cut size and coordinates calculation, but I don’t know what is there to explain. If you suck in math, than just copy paste it and live your miserable life :)

function create_thumb( $source_path, $destination_path, $thumb_width, $thumb_height, $quality=85, $overwrite=true ) {

    // If overwrite is set to FALSE and destination file allready exists, than return FALSE and quit execution
    if( file_exists( $destination_path ) && is_file( $destination_path ) && $overwrite == false ) return false;

    // Needed definitions
    $allowed_extensions = array( 'jpg', 'jpeg', 'png', 'gif' );

    $pathinfo = pathinfo( $source_path );

    // Check if source file exists, and is in array of allowed extensions.
    // Otherwise return FALSE
    if( file_exists( $source_path ) && in_array( strtolower( $pathinfo['extension'] ), $allowed_extensions ) )
    {

      // Get needed data about source image
      list( $original_width, $original_height, $type, $attr ) = getimagesize( $source_path );

      // Calculate cut size and coordinates
      $thumb_ratio = $thumb_width / $thumb_height;
      $original_ratio = $original_width / $original_height;

      if( $thumb_ratio > $original_ratio )
      {

          $cut_width  = $original_width;
          $cut_height = ( $original_width * $thumb_height ) / $thumb_width;

          $cut_x = 0;
          $cut_y = 0;

      }
      elseif( $thumb_ratio < $original_ratio )
      {

          $cut_width  = ( $original_height * $thumb_width ) / $thumb_height;
          $cut_height = $original_height;

          $cut_x = ( $original_width - $cut_width ) / 2;
          $cut_y = 0;

      }
      else
      {

          $cut_width  = $original_width;
          $cut_height = $original_height;

          $cut_x = 0;
          $cut_y = 0;

      }

      // Create final image layout
      $final_image = imagecreatetruecolor( $thumb_width, $thumb_height );

      // Is gif
      if( $pathinfo['extension'] == 'gif' )
      {
      	$source_image = imagecreatefromgif( $source_path );
      }
      // Is png
      elseif( $pathinfo['extension'] == 'png' )
      {
      	$source_image = imagecreatefrompng( $source_path );
      }
      // Is jpg, jpeg
      else
      {
      	$source_image = imagecreatefromjpeg( $source_path );
      }

      // Cut, resize source, and create final image
      imagecopyresampled( $final_image, $source_image, 0, 0, $cut_x, $cut_y, $thumb_width, $thumb_height, $cut_width, $cut_height );

      // Return TRUE if the thumbnail was created. Otherwise FALSE
      if ( imagejpeg( $final_image, $destination_path, $quality ) )
      {
        return true;
      }
      else
      {
        return false;
      }

    }
    else
    {
      return false;
    }

}

As you may notice, this function will always create a .jpg image. You can easily modify that to generate the same image type as source, but .jpg is simply the best choice for thumbnail, and it is not creating such mess on ftp as various image types. (If you are uploading animated gif, the first frame will be your thumbnail)

1.) Generate thumbnail by original image resolution ratio

This function will generate a thumbnail, which will fit into max thumbnail width and max height set by you, but also it will preserve the resolution image ratio of original, so it will be not deformed. Advantages and disadvantages of this method are exact opposite of previous one. Whole image is preserve in minified version, but on website, it could looks awful. Depends on how and where you are planning to use these thumbnails.
For better understanding, click on the image below.

thumb-ratio-cut-explanation

Definition and parameters are exactly same, just function is called create_ratio_thumb. Differences are highlighted.

function create_ratio_thumb( $source_path, $destination_path, $thumb_width, $thumb_height, $quality=85, $overwrite=true ) {

    // If overwrite is set to FALSE and destination file allready exists, than return FALSE and quit execution
    if( file_exists( $destination_path ) && is_file( $destination_path ) && $overwrite == false ) return false;

    // Needed definitions
    $allowed_extensions = array( 'jpg', 'jpeg', 'png', 'gif' );

    $pathinfo = pathinfo( $source_path );

    // Check if source file exists, and is in array of allowed extensions.
    // Otherwise return FALSE
    if( file_exists( $source_path ) && in_array( strtolower( $pathinfo['extension'] ), $allowed_extensions ) )
    {

      // Get needed data about source image
      list( $original_width, $original_height, $type, $attr ) = getimagesize( $source_path );

      // Calculate final thumbnail resolution
      $thumb_ratio = $thumb_width / $thumb_height;
      $original_ratio = $original_width / $original_height;

      if( $thumb_ratio > $original_ratio )
      {

          $final_width  = round( ( $thumb_height * $original_width) / $original_height );
          $final_height = $thumb_height;

      }
      elseif( $thumb_ratio < $original_ratio )
      {

          $final_width  = $thumb_width;
          $final_height = round( ( $thumb_width * $original_height ) / $original_width );

      }
      else
      {

          $final_width  = $thumb_width;
          $final_height = $thumb_height;

      }

      // Create final image layout
  		$final_image = imagecreatetruecolor( $final_width, $final_height );

  		// Is gif
  		if( $pathinfo['extension'] == 'gif' )
  		{
  			$source_image = imagecreatefromgif( $source_path );
  		}
  		// Is png
  		elseif( $pathinfo['extension'] == 'png' )
  		{
  			$source_image = imagecreatefrompng( $source_path );
  		}
  		// Is jpg, jpeg
  		else
  		{
  			$source_image = imagecreatefromjpeg( $source_path );
  		}

  		// Resize source, and create the final image
  		imagecopyresampled( $final_image, $source_image, 0, 0, 0, 0, $final_width, $final_height, $original_width, $original_height );

      // Return TRUE if the thumbnail was created. Otherwise FALSE
      if ( imagejpeg( $final_image, $destination_path, $quality ) )
      {
        return true;
      }
      else
      {
        return false;
      }

    }
    else
    {
      return false;
    }

}

And that would be our tutorial on creating thumbnails :) Check out the demo, where you can try to generate thumbnail from your own image, or download the tutorial files. (and don’t forget to set chmod 0777 to destination folder)

icon

Demo presentation

325x
icon

Tutorial files

10.30KB 203x