<?php

/**
 * THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 *
 * @package fusionLib
 * @copyright Copyright (c) 2013 fusionLib. All rights reserved.
 * @link http://fusionlib.com
 */

/**
 * flImageFilterSepia2 Class
 *
 * Image filter to give an image a sepia look using maths to transform the image.
 *
 * @package fusionLib
 */
class flImageFilterSepia2 {

	/**
	 * Apply the filter to the image.
	 *
	 * @param flImage $image The image object.
	 */
	function apply($image) {
		// http://www.techrepublic.com/blog/howdoi/how-do-i-convert-images-to-grayscale-and-sepia-tone-using-c/120
		$image = $image->getImageResource();
		$width = imagesx($image);
		$height = imagesy($image);
		for($x=0; $x<$width; $x++) {
			for($y=0; $y<$height; $y++) {
				$rgb = imagecolorat($image, $x, $y);
				$r = ($rgb >> 16) & 0xff;
				$g = ($rgb >> 8) & 0xff;
				$b = $rgb & 0xff;

				imagesetpixel($image, $x, $y, imagecolorallocate($image,
					min(255, ($r * .430) + ($g * .669) + ($b * .289)),
					min(255, ($r * .349) + ($g * .686) + ($b * .168)),
					min(255, ($r * .272) + ($g * .634) + ($b * .131))
				));
			}
		}
		imagefilter($image, IMG_FILTER_BRIGHTNESS, -30);
	}
}
