Create thumbnail with PHP (1)

PHP can be used to create and manipulate image files in a variety of different image formats. This post shows how to create thumbnail image in the same directory as the original image. Instead of GD library, I used utilities from ImageMagick suite of tools so your PHP shouldn’t have a GD module installed. convert with “-channel a” option will save transparency of the PNG and GIF images.

If you are looking for GD version of PHP thumbnail function, please see Create thumbnail with PHP (2).

/**
 * function creates a thumbnail image in the same directory with the prefix 'tn'
 * thumb should fit to the defined box (second parameter)
 * only bigger images are processed, while smaller images are just copied
 * function preserves PNG and GIF transparency
 *
 * @param string  $image1_path - full path to the image
 * @param integer $box         - box dimension
 */
function create_thumb($image1_path, $box=200){
	// get image size
	$identify = shell_exec("identify $image1_path");
	// read image geometry
	preg_match('/(\d+)x(\d+)/', $identify, $matches);
	$g1      = $matches[0]; // image geometry
	$width1  = $matches[1]; // image width
	$height1 = $matches[2]; // image height

	// prepare thumb name in the same directory with prefix 'tn'
	$image2_path = dirname($image1_path) . '/tn_' .basename($image1_path);
	
	// make image smaller if doesn't fit to the box 
	if ($width1 > $box || $height1 > $box){
		// set the largest dimension
		$width2 = $height2 = $box;
		// calculate smaller thumb dimension (proportional)
		if ($width1 < $height1) $width2  = round(($box / $height1) * $width1);
		else                    $height2 = round(($box / $width1) * $height1);
		
		// set thumbnail geometry
		$g2 = $width2 .'x' .$height2;
		
		// save thumbnail image to the file
		system("convert -channel a -size $g1 $image1_path -resize $g2 $image2_path");
	}
	// else just copy the image
	else copy($image1_path, $image2_path);
}

I also wrote Resize images with PHP where you can read about resizing all JPG images inside a current directory. After saving images from my camera to the computer, I needed a tool to prepare images for the Web upload. With small command line PHP script, images are converted to the lower resolution and saved to the separate subdirectory.

Categories PHP

Leave a Comment