Skip to content

Instantly share code, notes, and snippets.

@tj

tj/constrain.php

Created Mar 13, 2009
Embed
What would you like to do?
<?php
/**
* Copyright (c) 2009 TJ Holowaychuk <tj@vision-media.ca>
* 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