» Programming » php » imagemagick.php

<?php

final class imagemagick
{
	private static $instance;
	
	public function __construct()
	{
	}
	
	public static function instance()
	{
		if( !isset( self::$instance ) )
		{
			$class = __CLASS__;
			self::$instance = new $class;
		}
		return self::$instance;
	}
	
	public function crop_image( $width, $height, $infile, $outfile, $quality=75 )
	{
		if( file_exists( $infile ) )
		{
			$file_info = trim( `identify $infile` );
			$info_parts = explode( " ", $file_info );
			$geom = $info_parts[ 2 ];
			list( $cur_width, $cur_height ) = explode( "x", $geom );
			
			$scale_width = $width;
			$scale_height = ( $cur_height * ( $scale_width / $cur_width ) );
			if( $scale_height < $height )
			{
				$scale_height = $height;
				$scale_width = ( $cur_width * ( $height / $cur_height ) );
			}
			$offset_height = abs( $height - $scale_height ) / 2;
			$offset_width = abs( $width - $scale_width ) / 2;
			
			$con_cmd = sprintf( "convert -quality %d -scale %dx%d %s %s", $quality, $scale_width, $scale_height, $infile, $outfile );
			system( $con_cmd );
			$mog_cmd = sprintf( "mogrify -quality %d -crop %dx%d+%d+%d %s", $quality, $width, $height, $offset_width, $offset_height, $outfile );
			system( $mog_cmd );
		}
	}
	
	public function fit_image( $width, $height, $infile, $outfile, $quality=75 )
	{
		if( file_exists( $infile ) )
		{
			$file_info = trim( `identify $infile` );
			$info_parts = explode( " ", $file_info );
			$geom = $info_parts[ 2 ];
			list( $cur_width, $cur_height ) = explode( "x", $geom );
			
			if( $cur_width >= $width || $cur_height >= $height )
			{
				$wh_ratio = $cur_width / $cur_height;
				$scale_width = $width;
				$scale_height = ( $scale_width / $wh_ratio );
				if( $scale_height > $height )
				{
					$scale_height = $height;
					$scale_width = ( $scale_height * $wh_ratio );
				}
			}
			else
			{
				$scale_width = $cur_width;
				$scale_height = $cur_height;
			}
			$con_cmd = sprintf( "convert -quality %d -scale %dx%d %s %s", $quality, $scale_width, $scale_height, $infile, $outfile );
			system( $con_cmd );
		}
	}
	
}

?>
Creative Commons License
All works on this site are licensed under a Creative Commons Attribution-Share Alike 2.5 License.