GD.php 14 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505
<?php
/**
 * A wrapper class for GD-based images, with lots of manipulation functions.
 * @package framework
 * @subpackage filesystem
 */
class GDBackend extends Object implements Image_Backend {
	protected $gd, $width, $height;
	protected $quality;
	protected $interlace;
	
	/**
	 * @config
	 * @var integer
	 */
	private static $default_quality = 75;

	/**
	 * @config
	 * @var integer
	 */
	private static $image_interlace = 0;

	/**
	 * Set the default image quality.
	 *
	 * @deprecated 3.2 Use the "GDBackend.default_quality" config setting instead
	 * @param quality int A number from 0 to 100, 100 being the best quality.
	 */
	public static function set_default_quality($quality) {
		Deprecation::notice('3.2', 'Use the "GDBackend.default_quality" config setting instead');
		if(is_numeric($quality) && (int) $quality >= 0 && (int) $quality <= 100) {
			config::inst()->update('GDBackend', 'default_quality', (int) $quality);
		}
	}

	public function __construct($filename = null) {
		// If we're working with image resampling, things could take a while.  Bump up the time-limit
		increase_time_limit_to(300);

		if($filename && is_readable($filename)) {
			// We use getimagesize instead of extension checking, because sometimes extensions are wrong.
			list($width, $height, $type, $attr) = getimagesize($filename);
			switch($type) {
				case 1:
					if(function_exists('imagecreatefromgif'))
						$this->setImageResource(imagecreatefromgif($filename));
					break;
				case 2:
					if(function_exists('imagecreatefromjpeg'))
						$this->setImageResource(imagecreatefromjpeg($filename));
					break;
				case 3:
					if(function_exists('imagecreatefrompng')) {
						$img = imagecreatefrompng($filename);
						imagesavealpha($img, true); // save alphablending setting (important)
						$this->setImageResource($img);
					}
					break;
			}
		}
		
		parent::__construct();

		$this->quality = $this->config()->default_quality;
		$this->interlace = $this->config()->image_interlace;
	}
	
	public function setImageResource($resource) {
		$this->gd = $resource;
		$this->width = imagesx($resource);
		$this->height = imagesy($resource);
	}

	public function setGD($gd) {
		Deprecation::notice('3.1', 'Use GD::setImageResource instead');
		return $this->setImageResource($gd);
	}
	
	public function getImageResource() {
		return $this->gd;
	}

	public function getGD() {
		Deprecation::notice('3.1', 'GD::getImageResource instead');
		return $this->getImageResource();
	}

	/**
	 * Set the image quality, used when saving JPEGs.
	 */
	public function setQuality($quality) {
		$this->quality = $quality;
	}
	
	/**
	 * Resize an image to cover the given width/height completely, and crop off any overhanging edges.
	 */
	public function croppedResize($width, $height) {
		if(!$this->gd) return;
		
		$width = round($width);
		$height = round($height);
		
		// Check that a resize is actually necessary.
		if ($width == $this->width && $height == $this->height) {
			return $this;
		}
		
		$newGD = imagecreatetruecolor($width, $height);
		
		// Preserves transparency between images
		imagealphablending($newGD, false);
		imagesavealpha($newGD, true);
		
		$destAR = $width / $height;
		if ($this->width > 0 && $this->height > 0 ){
			// We can't divide by zero theres something wrong.
			
			$srcAR = $this->width / $this->height;
		
			// Destination narrower than the source
			if($destAR < $srcAR) {
				$srcY = 0;
				$srcHeight = $this->height;
				
				$srcWidth = round( $this->height * $destAR );
				$srcX = round( ($this->width - $srcWidth) / 2 );
			
			// Destination shorter than the source
			} else {
				$srcX = 0;
				$srcWidth = $this->width;
				
				$srcHeight = round( $this->width / $destAR );
				$srcY = round( ($this->height - $srcHeight) / 2 );
			}
			
			imagecopyresampled($newGD, $this->gd, 0,0, $srcX, $srcY, $width, $height, $srcWidth, $srcHeight);
		}
		$output = clone $this;
		$output->setImageResource($newGD);
		return $output;
	}
	
	/**
	 * Resizes the image to fit within the given region.
	 * Behaves similarly to paddedResize but without the padding.
	 * @todo This method isn't very efficent
	 */
	public function fittedResize($width, $height) {
		$gd = $this->resizeByHeight($height);
		if($gd->width > $width) $gd = $gd->resizeByWidth($width);
		return $gd;
	}
	
	/**
	 * hasImageResource
	 *
	 * @return boolean
	 */
	public function hasImageResource() {
		return $this->gd ? true : false;
	}
	
	public function hasGD() {
		Deprecation::notice('3.1', 'GD::hasImageResource instead',
			Deprecation::SCOPE_CLASS);
		return $this->hasImageResource();
	}
	
	
	/**
	 * Resize an image, skewing it as necessary.
	 */
	public function resize($width, $height) {
		if(!$this->gd) return;
		
		if($width < 0 || $height < 0) throw new InvalidArgumentException("Image resizing dimensions cannot be negative");
		if(!$width && !$height) throw new InvalidArgumentException("No dimensions given when resizing image");
		if(!$width) throw new InvalidArgumentException("Width not given when resizing image");
		if(!$height) throw new InvalidArgumentException("Height not given when resizing image");

		//use whole numbers, ensuring that size is at least 1x1
		$width = max(1, round($width));
		$height = max(1, round($height));
		
		// Check that a resize is actually necessary.
		if ($width == $this->width && $height == $this->height) {
			return $this;
		}

		$newGD = imagecreatetruecolor($width, $height);
		
		// Preserves transparency between images
		imagealphablending($newGD, false);
		imagesavealpha($newGD, true);

		imagecopyresampled($newGD, $this->gd, 0,0, 0, 0, $width, $height, $this->width, $this->height);

		$output = clone $this;
		$output->setImageResource($newGD);
		return $output;
	}
	
	/**
	 * Rotates image by given angle.
	 * 
	 * @param angle 
	 *
	 * @return GD 
	*/ 
	
	public function rotate($angle) {
		if(!$this->gd) return;
		
		if(function_exists("imagerotate")) {
			$newGD = imagerotate($this->gd, $angle,0);
		} else {
			//imagerotate is not included in PHP included in Ubuntu
			$newGD = $this->rotatePixelByPixel($angle);	
		}
		$output = clone $this;
		$output->setImageResource($newGD);
		return $output;
	}
	
	/**
	 * Rotates image by given angle. It's slow because makes it pixel by pixel rather than
	 * using built-in function. Used when imagerotate function is not available(i.e. Ubuntu)
	 * 
	 * @param angle 
	 *
	 * @return GD 
	*/ 
	
	public function rotatePixelByPixel($angle) {
		$sourceWidth = imagesx($this->gd);
		$sourceHeight = imagesy($this->gd);
		if ($angle == 180) {
			$destWidth = $sourceWidth;
			$destHeight = $sourceHeight;
		} else {
			$destWidth = $sourceHeight;
			$destHeight = $sourceWidth;
		}
		$rotate=imagecreatetruecolor($destWidth,$destHeight);
		imagealphablending($rotate, false);
		for ($x = 0; $x < ($sourceWidth); $x++) {
			for ($y = 0; $y < ($sourceHeight); $y++) {
				$color = imagecolorat($this->gd, $x, $y);
				switch ($angle) {
					case 90:
						imagesetpixel($rotate, $y, $destHeight - $x - 1, $color);
					break;
					case 180:
						imagesetpixel($rotate, $destWidth - $x - 1, $destHeight - $y - 1, $color);
					break;
					case 270:
						imagesetpixel($rotate, $destWidth - $y - 1, $x, $color);
					break;
					default: $rotate = $this->gd;
				};
			}
		}
		return $rotate;
	}
	
	
	/**
	 * Crop's part of image.
	 * 
	 * @param top y position of left upper corner of crop rectangle 
	 * @param left x position of left upper corner of crop rectangle
	 * @param width rectangle width
	 * @param height rectangle height
	 *
	 * @return GD  
	*/ 
	
	public function crop($top, $left, $width, $height) {
		$newGD = imagecreatetruecolor($width, $height);

		// Preserve alpha channel between images
		imagealphablending($newGD, false);
		imagesavealpha($newGD, true);

		imagecopyresampled($newGD, $this->gd, 0, 0, $left, $top, $width, $height, $width, $height);
		
		$output = clone $this;
		$output->setImageResource($newGD);
		return $output;
	}
	
	/**
	 * Method return width of image.
	 *
	 * @return integer width.
	*/ 
	public function getWidth() {
		return $this->width;
	}
	
	/**
	 * Method return height of image.
	 *
	 * @return integer height 
	*/ 
	
	public function getHeight() {
		return $this->height;
	}
	
	/**
	 * Resize an image by width. Preserves aspect ratio.
	 */
	public function resizeByWidth( $width ) {
		$heightScale = $width / $this->width;
		return $this->resize( $width, $heightScale * $this->height );
	}
	
	/**
	 * Resize an image by height. Preserves aspect ratio
	 */
	public function resizeByHeight( $height ) {
		$scale = $height / $this->height;
		return $this->resize( $scale * $this->width, $height );
	}
	
	/**
	 * Resize the image by preserving aspect ratio. By default, it will keep the image inside the maxWidth
	 * and maxHeight. Passing useAsMinimum will make the smaller dimension equal to the maximum corresponding dimension
	 */
	public function resizeRatio( $maxWidth, $maxHeight, $useAsMinimum = false ) {
		
		$widthRatio = $maxWidth / $this->width;
		$heightRatio = $maxHeight / $this->height;
		
		if( $widthRatio < $heightRatio )
			return $useAsMinimum ? $this->resizeByHeight( $maxHeight ) : $this->resizeByWidth( $maxWidth );
		else
			return $useAsMinimum ? $this->resizeByWidth( $maxWidth ) : $this->resizeByHeight( $maxHeight );
	}
	
	public static function color_web2gd($image, $webColor) {
		if(substr($webColor,0,1) == "#") $webColor = substr($webColor,1);
		$r = hexdec(substr($webColor,0,2));
		$g = hexdec(substr($webColor,2,2));
		$b = hexdec(substr($webColor,4,2));
		
		return imagecolorallocate($image, $r, $g, $b);
		
	}

	/**
	 * Resize to fit fully within the given box, without resizing.  Extra space left around
	 * the image will be padded with the background color.
	 * @param width
	 * @param height
	 * @param backgroundColour
	 */
	public function paddedResize($width, $height, $backgroundColor = "FFFFFF") {
		if(!$this->gd) return;
		$width = round($width);
		$height = round($height);
		
		// Check that a resize is actually necessary.
		if ($width == $this->width && $height == $this->height) {
			return $this;
		}
		
		$newGD = imagecreatetruecolor($width, $height);
		
		// Preserves transparency between images
		imagealphablending($newGD, false);
		imagesavealpha($newGD, true);
		
		$bg = GD::color_web2gd($newGD, $backgroundColor);
		imagefilledrectangle($newGD, 0, 0, $width, $height, $bg);
		
		$destAR = $width / $height;
		if ($this->width > 0 && $this->height > 0) {
			// We can't divide by zero theres something wrong.
			
			$srcAR = $this->width / $this->height;
		
			// Destination narrower than the source
			if($destAR > $srcAR) {
				$destY = 0;
				$destHeight = $height;
				
				$destWidth = round( $height * $srcAR );
				$destX = round( ($width - $destWidth) / 2 );
			
			// Destination shorter than the source
			} else {
				$destX = 0;
				$destWidth = $width;
				
				$destHeight = round( $width / $srcAR );
				$destY = round( ($height - $destHeight) / 2 );
			}
			
			imagecopyresampled($newGD, $this->gd,
				$destX, $destY, 0, 0,
				$destWidth, $destHeight, $this->width, $this->height);
		}
		$output = clone $this;
		$output->setImageResource($newGD);
		return $output;
	}

	/**
	 * Make the image greyscale
	 * $rv = red value, defaults to 38
	 * $gv = green value, defaults to 36
	 * $bv = blue value, defaults to 26
	 * Based (more or less entirely, with changes for readability) on code from
	 * http://www.teckis.com/scriptix/thumbnails/teck.html
	 */
	public function greyscale($rv=38, $gv=36, $bv=26) {
		$width = $this->width;
		$height = $this->height;
		$newGD = imagecreatetruecolor($this->width, $this->height);
		
		// Preserves transparency between images
		imagealphablending($newGD, false);
		imagesavealpha($newGD, true);
		
		$rt = $rv + $bv + $gv;
		$rr = ($rv == 0) ? 0 : 1/($rt/$rv);
		$br = ($bv == 0) ? 0 : 1/($rt/$bv);
		$gr = ($gv == 0) ? 0 : 1/($rt/$gv);
		for($dy = 0; $dy < $height; $dy++) {
			for($dx = 0; $dx < $width; $dx++) {
				$pxrgb = imagecolorat($this->gd, $dx, $dy);
				$heightgb = ImageColorsforIndex($this->gd, $pxrgb);
				$newcol = ($rr*$heightgb['red']) + ($br*$heightgb['blue']) + ($gr*$heightgb['green']);
				$setcol = ImageColorAllocateAlpha($newGD, $newcol, $newcol, $newcol, $heightgb['alpha']);
				imagesetpixel($newGD, $dx, $dy, $setcol);
			}
		}
		
		$output = clone $this;
		$output->setImageResource($newGD);
		return $output;
	}
	
	public function makeDir($dirname) {
		if(!file_exists(dirname($dirname))) $this->makeDir(dirname($dirname));
		if(!file_exists($dirname)) mkdir($dirname, Config::inst()->get('Filesystem', 'folder_create_mask'));
	}
	
	public function writeTo($filename) {
		$this->makeDir(dirname($filename));
		
		if($filename) {
			if(file_exists($filename)) list($width, $height, $type, $attr) = getimagesize($filename);
			
			if(file_exists($filename)) unlink($filename);

			$ext = strtolower(substr($filename, strrpos($filename,'.')+1));
			if(!isset($type)) switch($ext) {
				case "gif": $type = IMAGETYPE_GIF; break;
				case "jpeg": case "jpg": case "jpe": $type = IMAGETYPE_JPEG; break;
				default: $type = IMAGETYPE_PNG; break;
			}

			// if $this->interlace != 0, the output image will be interlaced
			imageinterlace ($this->gd, $this->interlace);
			
			// if the extension does not exist, the file will not be created!
			
			switch($type) {
				case IMAGETYPE_GIF: imagegif($this->gd, $filename); break;
				case IMAGETYPE_JPEG: imagejpeg($this->gd, $filename, $this->quality); break;
				
				// case 3, and everything else
				default: 
					// Save them as 8-bit images
					// imagetruecolortopalette($this->gd, false, 256);
					imagepng($this->gd, $filename); break;
			}
			if(file_exists($filename)) @chmod($filename,0664);
		}
	}
	
}

/**
 * This class is maintained for backwards-compatibility only. Please use the {@link GDBackend} class instead.
 *
 * @package framework
 * @subpackage filesystem
 */
class GD extends GDBackend {

	/**
	 * @deprecated 3.2 Use the "GDBackend.default_quality" config setting instead
	 */
	public static function set_default_quality($quality) {
		Deprecation::notice('3.2', 'Use the "GDBackend.default_quality" config setting instead');
		GDBackend::set_default_quality($quality);
	}	
}