Scaling images with ImageMagick and PHP 1

Posted by Dan Sosedoff on March 20, 2009

Here is php version of ruby class that i made a long time ago. The same functionality and results.

<?
class ImageScale {
 
	private function changeGeometry($sz,$value) {
		if ($sz['width'] > $sz['height']) { // horizontal image
			$newsz['width'] = $value;
			$newsz['height'] = ceil(($newsz['width'] * $sz['height']) / $sz['width']);
		}
		else { // vertical image
			$newsz['height'] = $value;
			$newsz['width'] = ceil(($newsz['height'] * $sz['width']) / $sz['height']);
		}
		return $newsz;	
	}
 
	private function changeGeometry2($sz,$value) {
		$newsz['width'] = $value;
		$newsz['height'] = ceil(($newsz['width'] * $sz['height']) / $sz['width']);
		return $newsz;
	}
 
	/**
	 * 	Make thumbnail of specified maximum side size
	 */
	public function processThumb($source_path, $dest_path, $sidesize, $quality=85, $scale_method=1) {
		if (file_exists($source_path) && is_readable($source_path)) {
			$image = new Imagick($source_path);
 
			$geometry = $image->getImageGeometry(); // ['width', 'height']
			if ($geometry['width'] > $sidesize) {
				if ($scale_method == 1) $geometry = $this->changeGeometry($geometry,$sidesize);
				if ($scale_method == 2) $geometry = $this->changeGeometry2($geometry,$sidesize);
			}
			$image->cropThumbnailImage($geometry['width'],$geometry['height']);
			$image->setCompression(Imagick::COMPRESSION_JPEG);
			$image->setCompressionQuality($quality);
			return $image->writeImage($dest_path);
		}
		return false;
	}	
 
	/**
	 * 	Make square thumbnail
	 */
	public function processRectThumb($source_path, $dest_path, $size=150, $quality=85) {
		if (file_exists($source_path) && is_readable($source_path)) {
			$image = new Imagick($source_path);
 
			if ($image) {
				$image->cropThumbnailImage($size,$size);
				$image->setCompression(Imagick::COMPRESSION_JPEG);
				$image->setCompressionQuality($quality);
				return $image->writeImage($dest_path);
			}
		}
		return false;
	}
}
?>

Download file – http://files.sosedoff.com/1167c8db/

Trackbacks

Trackbacks are closed.

Comments

Comments are closed.

  1. CappY Sun, 17 May 2009 05:38:26 CDT

    I like your blog. It’s very useful. :)