PHP - Image processing

From XennisWiki
Jump to: navigation, search

In PHP it is possible with various command line tools to edit images.

Further informations: Image processing and -generation

Comparison of GD Library, GraphicsMagick and ImageMagick

<?php
/**
 * Change the size of a image. The function is used to compare
 * GD Library, ImageMagick and GraphicsMagick. 
 *
 * @param  string  $file     Image path
 * @param  string  $name      Name of the new image
 * @param  int     $maxWidth  Maximal width of the new image
 * @param  int     $maxHeight Maximal height of the new image
 * @param  string  $tpy       "gm", "im" or "gm"
 * @param  int     $quality   From 1 to 100 (best)
 * @return boolean $result    Success: true
 */
function resizeImage( $file, $name, $maxWidth, $maxHeight, $typ, $quality = 75) {
	
	$fileSize = getimagesize( $file );
	$width = $fileSize[0];
	$height = $fileSize[1];

	if( $width > $height ) {
		$factor = $maxWidth / $width;
	} else {
		$factor = $maxHeight / $height;
	}
	
	$newWidth = round( $width * $factor );
	$newHeight = round( $height * $factor );

	// Resize with GD Library (JPEG only!)	
	if( $typ === 'gd' ) {
		$oldImage = imagecreatefromjpeg( $file );
		$newImage = imagecreatetruecolor( $newWidth, $newHeight );
	
		$result = imagecopyresampled($newImage, $oldImage, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
		imagejpeg( $newImage, $name, $quality);
	}

	// Resize with ImageMagick (Path: /usr/bin/convert)
	else if( $typ === 'im' ) {
		$command = '/usr/bin/convert convert '.$file.' -resize '.$newWidth.'x'.$newHeight.' -quality '.$quality.'  '.$name;

		passthru($command, $result);
	}

	// Resize with GraphicsMagick (Path: /usr/bin/gm )
	else if( $typ === 'gm' ) {
		$command = '/usr/bin/gm convert '.$file.' -resize '.$newWidth.'x'.$newHeight.' -quality '.$quality.'  '.$name;

		passthru($command, $result);
	}

	return $result;
}
?>
<?php
resizeImage( 'sample_image.jpg', 'sample_image_small_gd.jpg', 350, 250, 'gd', 90 );
resizeImage( 'sample_image.jpg', 'sample_image_small_im.jpg', 350, 250, 'im', 90 );
resizeImage( 'sample_image.jpg', 'sample_image_small_gm.jpg', 350, 250, 'gm', 90 );
?>

External links

ImageMagick