Created
March 13, 2009 21:23
-
-
Save tj/78775 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Copyright (c) 2009 TJ Holowaychuk <[email protected]> | |
* MIT Licensed | |
*/ | |
define('GD_CONSTRAIN_DIMENSIONS_VERSION', '0.0.1'); | |
class GD_Constrain_Dimensions { | |
/** | |
* Input image filepath. | |
* | |
* @var string | |
*/ | |
public $input_path; | |
/** | |
* Output image filepath. | |
* | |
* @var string | |
*/ | |
public $output_path; | |
/** | |
* Output image quality. | |
* | |
* @var int | |
*/ | |
public $quality = 90; | |
/** | |
* Constructor. | |
* | |
* @param string $input_path | |
* Path to the input image. | |
* | |
* @param string $output_path | |
* (optional) Path to output image. Defaults to | |
* using the $input_path provided. | |
*/ | |
public function __construct($input_path, $output_path = NULL) { | |
$this->input_path = $input_path; | |
if ($output_path) $this->output_path = $output_path; | |
else $this->output_path = $input_path; | |
} | |
/** | |
* Convert the image to its constrained dimensions. | |
*/ | |
public function constrain($target_width, $target_height) { | |
if (!file_exists($this->input_path)) throw new Exception("input image '$this->input_path' does not exist"); | |
list($width, $height, $type, $attr) = getimagesize($this->input_path); | |
$img = imagecreatefromjpeg($this->input_path); | |
$canvas = imagecreatetruecolor($target_width, $target_height); | |
$white = imagecolorallocate($canvas, 255, 255, 255); | |
imagefill($canvas, 0, 0, $white); | |
$dest_x = $target_width / 2 - $width; | |
$dest_y = $target_height / 2 - $height; | |
if ($width > $height) $ratio = $target_width / $width; | |
else $ratio = $target_height / $height; | |
$dest_width = $width * $ratio; | |
$dest_height = $height * $ratio; | |
$dest_x = ($target_width / 2) - ($dest_width / 2); | |
$dest_y = ($target_height / 2) - ($dest_height / 2); | |
imagecopyresampled($canvas, $img, $dest_x, $dest_y, 0, 0, $dest_width, $dest_height, $width, $height); | |
imagejpeg($canvas, $this->output_path, $this->quality); | |
imagedestroy($img); | |
imagedestroy($canvas); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment