Source for file Transform.php
Documentation is available at Transform.php
/* vim: set expandtab tabstop=4 shiftwidth=4: */
* Simple and cross-library package to doing image transformations and
* LICENSE: This source file is subject to version 3.0 of the PHP license
* that is available through the world-wide-web at the following URI:
* http://www.php.net/license/3_0.txt. If you did not receive a copy of
* the PHP License and are unable to obtain it through the web, please
* send a note to license@php.net so we can mail you a copy immediately.
* @package Image_Transform
* @author Vincent Oostindie <vincent@sunlight.tmfweb.nl>
* @author Alan Knowles <alan@akbkhome.com>
* @author Peter Bowyer <peter@mapledesign.co.uk>
* @author Philippe Jausions <Philippe.Jausions@11abacus.com>
* @copyright 2002-2007 The PHP Group
* @license http://www.php.net/license/3_0.txt PHP License 3.0
* @version CVS: $Id: Transform.php 322659 2012-01-24 11:56:22Z clockwerx $
* @link http://pear.php.net/package/Image_Transform
* Include for error handling
* Error code for unsupported library, image format or methods
define('IMAGE_TRANSFORM_ERROR_UNSUPPORTED', 1 );
* Error code for failed transformation operations
define('IMAGE_TRANSFORM_ERROR_FAILED', 2 );
* Error code for failed i/o (Input/Output) operations
define('IMAGE_TRANSFORM_ERROR_IO', 3 );
* Error code for invalid arguments
define('IMAGE_TRANSFORM_ERROR_ARGUMENT', 4 );
* Error code for out-of-bound related errors
define('IMAGE_TRANSFORM_ERROR_OUTOFBOUND', 5 );
* Error code for inexsitant driver errors
define('IMAGE_TRANSFORM_DRIVER_FILE_MISSING', 6 );
* Base class with factory method for backend driver
* The main "Image_Transform" class is a container and base class which
* provides a static method for creating an Image object as well as
* some utility functions (maths) common to all parts of Image_Transform.
* @package Image_Transform
* @author Alan Knowles <alan@akbkhome.com>
* @author Peter Bowyer <peter@mapledesign.co.uk>
* @author Philippe Jausions <Philippe.Jausions@11abacus.com>
* @copyright 2002-2007 The PHP Group
* @license http://www.php.net/license/3_0.txt PHP License 3.0
* @version Release: @package_version@
* @link http://pear.php.net/package/Image_Transform
* Type of the image file (eg. jpg, gif png ...)
* Original image width in x direction
* Original image width in y direction
* New image width in x direction
* New image width in y direction
* Path to the library used
* e.g. /usr/local/ImageMagick/bin/ or
* Flag to warn if image has been resized more than once before displaying
* @var array General options
'scaleMethod' => 'smooth',
'canvasColor' => array (255 , 255 , 255 ),
'pencilColor' => array (0 , 0 , 0 ),
'textColor' => array (0 , 0 , 0 )
* Flag for whether settings should be discarded on saving/display of image
* @see Image_Transform::keepSettingsOnSave
* Initialization error tracking
* associative array that tracks existence of programs
* (for drivers using shell interface and a tiny performance
* improvement if the clearstatcache() is used)
* Default parameters used in the addText methods.
'text' => 'Default text',
* Creates a new Image_Transform object
* @param string $driver name of driver class to initialize. If no driver
* is specified the factory will attempt to use 'Imagick' first
* then 'GD' second, then 'Imlib' last
* @return object an Image_Transform object, or PEAR_Error on error
* @see Image_Transform::setOption()
//Imagick2 driver for php < 5
$extensions['imagick'] = 'Imagick2';
foreach ($extensions as $ext => $ext_driver) {
if (PEAR ::loadExtension ($ext)) {
'No image library specified and none can be found.'
. ' You must specify driver in factory() call.',
$file = 'Image/Transform/Driver/' . $driver . '.php';
return PEAR ::raiseError ('Driver failed to load file ' . $file,
$classname = 'Image_Transform_Driver_' . $driver;
'Image library ' . $driver . ' not supported... aborting.',
if ($error = & $obj->isError ()) {
* Returns/sets an error when the instance couldn't initialize properly
* @param object $error PEAR_Error object when setting an error
* @return mixed FALSE or PEAR_Error object
* Resizes the image in the X and/or Y direction(s)
* If either is 0 it will keep the original size for that dimension
* @param mixed $new_x (0, number, percentage 10% or 0.1)
* @param mixed $new_y (0, number, percentage 10% or 0.1)
* @param array $options Options
* @return mixed TRUE or PEAR_Error object on error
function resize($new_x = 0 , $new_y = 0 , $options = null )
// 0 means keep original size
// Now do the library specific resizing.
return $this->_resize($new_x, $new_y, $options);
* Scales the image to the specified width
* This method preserves the aspect ratio
* @param int $new_x Size to scale X-dimension to
* @return mixed TRUE or PEAR_Error object on error
return PEAR ::raiseError ('New size must be strictly positive',
function scaleByXY($new_x = 0 , $new_y = 0 , $options = null )
return $this->resize($new_x, $new_y, $options);
* Scales the image to the specified height.
* This method preserves the aspect ratio
* @param int $new_y Size to scale Y-dimension to
* @return mixed TRUE or PEAR_Error object on error
return PEAR ::raiseError ('New size must be strictly positive',
* Scales an image by a percentage, factor or a given length
* This method preserves the aspect ratio
* @param mixed $size (number, percentage 10% or 0.1)
* @return mixed TRUE or PEAR_Error object on error
* @see scaleByPercentage, scaleByFactor, scaleByLength
* Scales an image to a percentage of its original size. For example, if
* my image was 640x480 and I called scaleByPercentage(10) then the image
* would be resized to 64x48
* @param int $size Percentage of original size to scale to
* @return mixed TRUE or PEAR_Error object on error
} // End scaleByPercentage
* Scales an image to a factor of its original size. For example, if
* my image was 640x480 and I called scaleByFactor(0.5) then the image
* would be resized to 320x240.
* @param float $size Factor of original size to scale to
* @return mixed TRUE or PEAR_Error object on error
return PEAR ::raiseError ('New size must be strictly positive',
* Scales an image so that the longest side has the specified dimension.
* This method preserves the aspect ratio
* @param int $size Max dimension in pixels
* @return mixed TRUE or PEAR_Error object on error
return PEAR ::raiseError ('New size must be strictly positive',
* Alias for scaleMaxLength
* @param int $size Max dimension in pixels
* @return mixed TRUE or PEAR_Error object on error
* Fits the image in the specified box size
* If the image is bigger than the box specified by $width and $height,
* it will be scaled down to fit inside of it.
* If the image is smaller, nothing is done.
* @param integer $width Width of the box in pixels
* @param integer $height Height of the box in pixels
* @return bool|PEAR_ErrorTRUE or PEAR_Error object on error
function fit($width, $height)
if ($width <= 0 || $height <= 0 ) {
return PEAR ::raiseError ("Invalid arguments.",
$x = $this->img_x / $width;
$y = $this->img_y / $height;
if ($x <= 1 && $y <= 1 ) {
* This works as per fit, but creates the canvas of size $width x $height
* and positions the resized image on it, by default in the centre.
* @param unknown_type $width
* @param unknown_type $height
* @param unknown_type $posn
return PEAR ::raiseError ('fitOnCanvas() method not supported by driver',
* Fits the image in the specified width
* If the image is wider than the width specified by $width,
* it will be scaled down to fit inside of it.
* If the image is smaller, nothing is done.
* @param integer $width Maximum width in pixels
* @return bool|PEAR_ErrorTRUE or PEAR_Error object on error
return ($this->img_x <= $width) ? true : $this->scaleByX($width);
* Fits the image in the specified height
* If the image is taller than the height specified by $height,
* it will be scaled down to fit inside of it.
* If the image is smaller, nothing is done.
* @param integer $height Maximum height in pixels
* @return bool|PEAR_ErrorTRUE or PEAR_Error object on error
return ($this->img_y <= $height) ? true : $this->scaleByY($height);
* @param string $name Name of option
* @param mixed $value Value of option
* Sets multiple options at once
* Associative array of options:
* - quality (Integer: 0: poor - 100: best)
* - scaleMethod ('smooth', 'pixel')
* @param array $options Array of options
* Sets the image type (in lowercase letters), the image height and width.
* @param string $image Image filename
* @return mixed TRUE or PEAR_error
* @see PHP_Compat::image_type_to_mime_type()
* @link http://php.net/getimagesize
// 1 = GIF, 2 = JPG, 3 = PNG, 4 = SWF, 5 = PSD, 6 = BMP,
// 7 = TIFF (intel byte order), 8 = TIFF (motorola byte order),
// 9 = JPC, 10 = JP2, 11 = JPX, 12 = JB2, 13 = SWC, 14 = IFF,
return PEAR ::raiseError ("Cannot fetch image or images details.", true );
return PEAR ::raiseError ("Cannot recognize image format",
* Returns the matching IMAGETYPE_* constant for a given image type
* @param mixed $type String (GIF, JPG,...)
* @return mixed string or integer or input on error
* @see PHP_Compat::image_type_to_mime_type()
return IMAGETYPE_TIFF_II;
return (isset ($types[$t = strtolower($type)])) ? $types[$t] : $type;
* Parses input for number format and convert
* If either parameter is 0 it will be scaled proportionally
* @param mixed $new_size (0, number, percentage 10% or 0.1)
* @return mixed Integer or PEAR_error
if (substr($new_size, -1 ) == '%') {
$new_size = substr($new_size, 0 , -1 );
$new_size = $new_size / 100;
} elseif ($new_size == 0 ) {
return (int) round($new_size * $old_size, 0 );
* Returns an angle between 0 and 360 from any angle value
* @param float $angle The angle to normalize
* @return float the angle
return ($angle < 0 ) ? $angle + 360 : $angle;
* Returns the current value of $this->default_text_params.
* @return array $this->default_text_params The current text parameters
* @param int $size dimension to set
* @since 29/05/02 13:36:31
* @param int $size dimension to set
* @since 29/05/02 13:36:31
* Sets the new image width
* @param int $size dimension to set
* @since 29/05/02 13:36:31
* Sets the new image height
* @param int $size dimension to set
* @since 29/05/02 13:36:31
* Returns the image handle so that one can further try
* to manipulate the image
return PEAR ::raiseError ('getHandle() method not supported by driver',
* Returns the type of the image being manipulated
* @return string the image type
* Returns the MIME type of the image being manipulated
* @param string $type Image type to get MIME type for
* @return string The MIME type if available, or an empty string
* @see PHP_Compat::image_type_to_mime_type()
* @link http://php.net/image_type_to_mime_type
* Returns the new image width
* This function returns the width
* @return int The width of the new image.
if (isset ($this->new_x)) {
return (int) $this->new_x;
* This function will retrieve the
* new image 'Y' and return it's value
* @return int The new height of the image.
if (isset ($this->new_y)) {
return (int) $this->new_y;
* Returns the image width
* @return int the width of the image
* Returns the image height
* @return int the width of the image
* Returns the image size and extra format information
* @return array The width and height of the image
* @see PHP::getimagesize()
'height="' . $this->img_y . '" width="' . $this->img_x . '"',
* This looks at the current image type and attempts to determine which
* web-safe format will be most suited. It does not work brilliantly with
* *.png images, because it is very difficult to know whether they are
* 8-bit or greater. Guess I need to have fatter code here :-)
* @return string web-safe image type
* Handles space in path and Windows/UNIX difference
* @param string $path Base dir
* @param string $command Command to execute
* @param string $args Arguments to pass to the command
* @return string A prepared string suitable for exec()
return $path . $command . ' ' . $args;
return 'start /D "' . $path . '" /B ' . $command . ' ' . $args;
* Place holder for the real resize method
* used by extended methods to do the resizing
return PEAR ::raiseError ('Resize method not supported by driver',
* Normalizes the colors, gamma and other properties of an image
* (this should give a result equivalent to a Photoshop autolevels)
return PEAR ::raiseError ('Normalize method not supported by driver',
* Loads an image file to work with
* Place holder for the real load method
* used by extended methods to do the resizing
* @param string $filename Full name of file
return PEAR ::raiseError ('load() method not supported by driver',
* Outputs the image to standard output
* Place holder for the real display method
* used by extended methods to do the resizing
* @param string $type Format of image to save as
* @param mixed $quality Format-dependent
function display($type, $quality = null )
return PEAR ::raiseError ('display() method not supported by driver',
* Returns if the driver supports a given image type
* @param string $type Image type (GIF, PNG, JPEG...)
* @param string $mode 'r' for read, 'w' for write, 'rw' for both
* @return TRUE if type (and mode) is supported FALSE otherwise
* Place holder for the real save method
* used by extended methods to do the resizing
* @param string $filename Filename to save image to
* @param string $type Format of image to save as
* @param mixed $quality Format-dependent
function save($filename, $type, $quality = null )
return PEAR ::raiseError ('save() method not supported by driver',
* Place holder for the real free method
* used by extended methods to do the resizing
return PEAR ::raiseError ('free() method not supported by driver',
* Converts a color string into an array of RGB values
* @param string $colorhex A color following the #FFFFFF format
* @return array 3-element array with 0-255 values
* @see colorarray2colorhex
return array ($r, $g, $b, 'type' => 'RGB');
function _send_display_headers ($type)
// Find the filename of the original image:
$filename = $filename[0 ];
header('Content-Disposition: inline; filename=' . $filename . '.' . $type);
* Converts an array of RGB value into a #FFFFFF format color.
* @param array $color 3-element array with 0-255 values
* @return mixed A color following the #FFFFFF format or FALSE
* if the array couldn't be converted
* @see colorhex2colorarray
$color = sprintf('#%02X%02X%02X', @$color[0 ], @$color[1 ], @$color[2 ]);
return (strlen($color) != 7 ) ? false : $color;
* Returns the temp directory according to either the TMP, TMPDIR, or TEMP env
* variables. If these are not set it will also check for the existence of
* @return string The system tmp directory
include_once 'System.php';
* Returns a temporary filename using tempnam() and the above getTmpDir() function.
* @param string $dirname Optional directory name for the tmp file
* @return string Filename and path of the tmp file
include_once 'System.php';
$dirname = System ::tmpdir ();
* Methods to add to the driver classes in the future
return PEAR ::raiseError ('addText() method not supported by driver',
return PEAR ::raiseError ('addDropShadow() method not supported by driver',
return PEAR ::raiseError ('addBorder() method not supported by driver',
* @param int $width Cropped image width
* @param int $height Cropped image height
* @param int $x X-coordinate to crop at
* @param int $y Y-coordinate to crop at
* @return mixed TRUE or a PEAR_Error object on error
function crop($width, $height, $x = 0 , $y = 0 )
return PEAR ::raiseError ('crop() method not supported by driver',
return PEAR ::raiseError ('canvasResize() method not supported by driver',
* Corrects the gamma of an image
* @param float $outputgamma Gamma correction factor
* @return mixed TRUE or a PEAR_error object on error
function gamma($outputgamma = 1.0 )
return PEAR ::raiseError ('gamma() method not supported by driver',
* Rotates the image clockwise
* @param float $angle Angle of rotation in degres
* @param mixed $options Rotation options
* @return bool|PEAR_ErrorTRUE on success, PEAR_Error object on error
function rotate($angle, $options = null )
return PEAR ::raiseError ('rotate() method not supported by driver',
* @return mixed TRUE or PEAR_Error object on error
return PEAR ::raiseError ('mirror() method not supported by driver',
* @return TRUE or PEAR Error object on error
return PEAR ::raiseError ('flip() method not supported by driver',
* Converts an image into greyscale colors
* @return mixed TRUE or a PEAR error object on error
return PEAR ::raiseError ('greyscale() method not supported by driver',
* Converts an image into greyscale colors
* @return mixed TRUE or a PEAR error object on error
* @param string $colorOf one of 'canvasColor', 'pencilColor', 'fontColor'
* @param array $options configuration options
* @param array $default default value to return if color not found
* @return array an RGB color array
function _getColor($colorOf, $options = array (), $default = array (0 , 0 , 0 ))
if (isset ($opt[$colorOf])) {
static $colornames = array ();
include_once 'Image/Transform/Driver/ColorsDefs.php';
return (isset ($colornames[$color])) ? $colornames[$color] : $default;
* @param string $name name of option
* @param array $options local override option array
* @param mixed $default default value to return if option is not found
* @return mixed the option
function _getOption($name, $options = array (), $default = null )
return (isset ($opt[$name])) ? $opt[$name] : $default;
* Checks if the rectangle passed intersects with the current image
* @param int $width Width of rectangle
* @param int $height Height of rectangle
* @param int $x X-coordinate
* @param int $y Y-coordinate
* @return bool|PEAR_ErrorTRUE if intersects, FALSE if not,
* and PEAR_Error on error
return (bool) ($left < $this->new_x
Documentation generated on Wed, 04 Apr 2012 00:30:11 +0000 by phpDocumentor 1.4.3. PEAR Logo Copyright © PHP Group 2004.
|