diff --git a/webroot/imgd.php b/webroot/imgd.php index 267e7d7..14949d1 100755 --- a/webroot/imgd.php +++ b/webroot/imgd.php @@ -38,7 +38,7 @@ $config = array( // Version of cimage and img.php -define("CIMAGE_VERSION", "v0.8.1 (2020-06-08)"); +define("CIMAGE_VERSION", "v0.8.2 (2021-10-27)"); // For CRemoteImage define("CIMAGE_USER_AGENT", "CImage/" . CIMAGE_VERSION); diff --git a/webroot/imgp.php b/webroot/imgp.php index 642ea94..e05db87 100755 --- a/webroot/imgp.php +++ b/webroot/imgp.php @@ -38,7 +38,7 @@ $config = array( // Version of cimage and img.php -define("CIMAGE_VERSION", "v0.8.1 (2020-06-08)"); +define("CIMAGE_VERSION", "v0.8.2 (2021-10-27)"); // For CRemoteImage define("CIMAGE_USER_AGENT", "CImage/" . CIMAGE_VERSION); diff --git a/webroot/imgs.php b/webroot/imgs.php index b7c61a0..69d94f3 100644 --- a/webroot/imgs.php +++ b/webroot/imgs.php @@ -1,5 +1,5 @@ 'strict', ); define("CIMAGE_VERSION", "v0.8.1 (2020-06-08)"); define("CIMAGE_USER_AGENT", "CImage/" . CIMAGE_VERSION); if (!defined("IMG_WEBP")) { define("IMG_WEBP", -1); } function trace($msg) { $file = CIMAGE_DEBUG_FILE; if (!is_writable($file)) { return; } $timer = number_format((microtime(true) - $_SERVER["REQUEST_TIME_FLOAT"]), 6); $details = "{$timer}ms"; $details .= ":" . round(memory_get_peak_usage()/1024/1024, 3) . "MB"; $details .= ":" . count(get_included_files()); file_put_contents($file, "$details:$msg\n", FILE_APPEND); } function errorPage($msg, $type = 500) { global $mode; switch ($type) { case 403: $header = "403 Forbidden"; break; case 404: $header = "404 Not Found"; break; default: $header = "500 Internal Server Error"; } if ($mode == "strict") { $header = "404 Not Found"; } header("HTTP/1.0 $header"); if ($mode == "development") { die("[img.php] $msg"); } error_log("[img.php] $msg"); die("HTTP/1.0 $header"); } function get($key, $default = null) { if (is_array($key)) { foreach ($key as $val) { if (isset($_GET[$val])) { return $_GET[$val]; } } } elseif (isset($_GET[$key])) { return $_GET[$key]; } return $default; } function getDefined($key, $defined, $undefined) { return get($key) === null ? $undefined : $defined; } function getValue($key, $undefined) { $val = get($key); if (is_null($val) || $val === "") { return $undefined; } return $val; } function getConfig($key, $default) { global $config; return isset($config[$key]) ? $config[$key] : $default; } function verbose($msg = null, $arg = "") { global $verbose, $verboseFile; static $log = array(); if (!($verbose || $verboseFile)) { return; } if (is_null($msg)) { return $log; } if (is_null($arg)) { $arg = "null"; } elseif ($arg === false) { $arg = "false"; } elseif ($arg === true) { $arg = "true"; } $log[] = $msg . $arg; } function checkExternalCommand($what, $enabled, $commandString) { $no = $enabled ? null : 'NOT'; $text = "Post processing $what is $no enabled.
"; list($command) = explode(" ", $commandString); $no = is_executable($command) ? null : 'NOT'; $text .= "The command for $what is $no an executable.
"; return $text; } class CHttpGet { private $request = array(); private $response = array(); public function __construct() { $this->request['header'] = array(); } public function buildUrl($baseUrl, $merge) { $parts = parse_url($baseUrl); $parts = array_merge($parts, $merge); $url = $parts['scheme']; $url .= "://"; $url .= $parts['host']; $url .= isset($parts['port']) ? ":" . $parts['port'] : "" ; $url .= $parts['path']; return $url; } public function setUrl($url) { $parts = parse_url($url); $path = ""; if (isset($parts['path'])) { $pathParts = explode('/', $parts['path']); unset($pathParts[0]); foreach ($pathParts as $value) { $path .= "/" . rawurlencode($value); } } $url = $this->buildUrl($url, array("path" => $path)); $this->request['url'] = $url; return $this; } public function setHeader($field, $value) { $this->request['header'][] = "$field: $value"; return $this; } public function parseHeader() { $rawHeaders = rtrim($this->response['headerRaw'], "\r\n"); $headerGroups = explode("\r\n\r\n", $rawHeaders); $header = explode("\r\n", end($headerGroups)); $output = array(); if ('HTTP' === substr($header[0], 0, 4)) { list($output['version'], $output['status']) = explode(' ', $header[0]); unset($header[0]); } foreach ($header as $entry) { $pos = strpos($entry, ':'); $output[trim(substr($entry, 0, $pos))] = trim(substr($entry, $pos + 1)); } $this->response['header'] = $output; return $this; } public function doGet($debug = false) { $options = array( CURLOPT_URL => $this->request['url'], CURLOPT_HEADER => 1, CURLOPT_HTTPHEADER => $this->request['header'], CURLOPT_AUTOREFERER => true, CURLOPT_RETURNTRANSFER => true, CURLINFO_HEADER_OUT => $debug, CURLOPT_CONNECTTIMEOUT => 5, CURLOPT_TIMEOUT => 5, CURLOPT_FOLLOWLOCATION => true, CURLOPT_MAXREDIRS => 2, ); $ch = curl_init(); curl_setopt_array($ch, $options); $response = curl_exec($ch); if (!$response) { throw new Exception("Failed retrieving url, details follows: " . curl_error($ch)); } $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE); $this->response['headerRaw'] = substr($response, 0, $headerSize); $this->response['body'] = substr($response, $headerSize); $this->parseHeader(); if ($debug) { $info = curl_getinfo($ch); echo "Request header
", var_dump($info['request_header']), "
"; echo "Response header (raw)
", var_dump($this->response['headerRaw']), "
"; echo "Response header (parsed)
", var_dump($this->response['header']), "
"; } curl_close($ch); return true; } public function getStatus() { return isset($this->response['header']['status']) ? (int) $this->response['header']['status'] : null; } public function getLastModified() { return isset($this->response['header']['Last-Modified']) ? strtotime($this->response['header']['Last-Modified']) : null; } public function getContentType() { $type = isset($this->response['header']['Content-Type']) ? $this->response['header']['Content-Type'] : null; return preg_match('#[a-z]+/[a-z]+#', $type) ? $type : null; } public function getDate($default = false) { return isset($this->response['header']['Date']) ? strtotime($this->response['header']['Date']) : $default; } public function getMaxAge($default = false) { $cacheControl = isset($this->response['header']['Cache-Control']) ? $this->response['header']['Cache-Control'] : null; $maxAge = null; if ($cacheControl) { $part = explode('=', $cacheControl); $maxAge = ($part[0] == "max-age") ? (int) $part[1] : null; } if ($maxAge) { return $maxAge; } $expire = isset($this->response['header']['Expires']) ? strtotime($this->response['header']['Expires']) : null; return $expire ? $expire : $default; } public function getBody() { return $this->response['body']; } } class CRemoteImage { private $saveFolder = null; private $useCache = true; private $http; private $status; private $defaultMaxAge = 604800; private $url; private $fileName; private $fileJson; private $cache; public function getStatus() { return $this->status; } public function getDetails() { return $this->cache; } public function setCache($path) { $this->saveFolder = rtrim($path, "/") . "/"; return $this; } public function isCacheWritable() { if (!is_writable($this->saveFolder)) { throw new Exception("Cache folder is not writable for downloaded files."); } return $this; } public function useCache($use = true) { $this->useCache = $use; return $this; } public function setHeaderFields() { $cimageVersion = "CImage"; if (defined("CIMAGE_USER_AGENT")) { $cimageVersion = CIMAGE_USER_AGENT; } $this->http->setHeader("User-Agent", "$cimageVersion (PHP/". phpversion() . " cURL)"); $this->http->setHeader("Accept", "image/jpeg,image/png,image/gif"); if ($this->useCache) { $this->http->setHeader("Cache-Control", "max-age=0"); } else { $this->http->setHeader("Cache-Control", "no-cache"); $this->http->setHeader("Pragma", "no-cache"); } } public function save() { $this->cache = array(); $date = $this->http->getDate(time()); $maxAge = $this->http->getMaxAge($this->defaultMaxAge); $lastModified = $this->http->getLastModified(); $type = $this->http->getContentType(); $this->cache['Date'] = gmdate("D, d M Y H:i:s T", $date); $this->cache['Max-Age'] = $maxAge; $this->cache['Content-Type'] = $type; $this->cache['Url'] = $this->url; if ($lastModified) { $this->cache['Last-Modified'] = gmdate("D, d M Y H:i:s T", $lastModified); } $body = $this->http->getBody(); $img = imagecreatefromstring($body); if ($img !== false) { file_put_contents($this->fileName, $body); file_put_contents($this->fileJson, json_encode($this->cache)); return $this->fileName; } return false; } public function updateCacheDetails() { $date = $this->http->getDate(time()); $maxAge = $this->http->getMaxAge($this->defaultMaxAge); $lastModified = $this->http->getLastModified(); $this->cache['Date'] = gmdate("D, d M Y H:i:s T", $date); $this->cache['Max-Age'] = $maxAge; if ($lastModified) { $this->cache['Last-Modified'] = gmdate("D, d M Y H:i:s T", $lastModified); } file_put_contents($this->fileJson, json_encode($this->cache)); return $this->fileName; } public function download($url) { $this->http = new CHttpGet(); $this->url = $url; $this->loadCacheDetails(); if ($this->useCache) { $src = $this->getCachedSource(); if ($src) { $this->status = 1; return $src; } } $this->setHeaderFields(); $this->http->setUrl($this->url); $this->http->doGet(); $this->status = $this->http->getStatus(); if ($this->status === 200) { $this->isCacheWritable(); return $this->save(); } elseif ($this->status === 304) { $this->isCacheWritable(); return $this->updateCacheDetails(); } throw new Exception("Unknown statuscode when downloading remote image: " . $this->status); } public function loadCacheDetails() { $cacheFile = md5($this->url); $this->fileName = $this->saveFolder . $cacheFile; $this->fileJson = $this->fileName . ".json"; if (is_readable($this->fileJson)) { $this->cache = json_decode(file_get_contents($this->fileJson), true); } } public function getCachedSource() { $imageExists = is_readable($this->fileName); $date = strtotime($this->cache['Date']); $maxAge = $this->cache['Max-Age']; $now = time(); if ($imageExists && $date + $maxAge > $now) { return $this->fileName; } if ($imageExists && isset($this->cache['Last-Modified'])) { $this->http->setHeader("If-Modified-Since", $this->cache['Last-Modified']); } return false; } } class CWhitelist { private $whitelist = array(); public function set($whitelist = array()) { if (!is_array($whitelist)) { throw new Exception("Whitelist is not of a supported format."); } $this->whitelist = $whitelist; return $this; } public function check($item, $whitelist = null) { if ($whitelist !== null) { $this->set($whitelist); } if (empty($item) or empty($this->whitelist)) { return false; } foreach ($this->whitelist as $regexp) { if (preg_match("#$regexp#", $item)) { return true; } } return false; } } class CAsciiArt { private $characterSet = array( 'one' => "#0XT|:,.' ", 'two' => "@%#*+=-:. ", 'three' => "$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. " ); private $characters = null; private $charCount = null; private $scale = null; private $luminanceStrategy = null; public function __construct() { $this->setOptions(); } public function addCharacterSet($key, $value) { $this->characterSet[$key] = $value; return $this; } public function setOptions($options = array()) { $default = array( "characterSet" => 'two', "scale" => 14, "luminanceStrategy" => 3, "customCharacterSet" => null, ); $default = array_merge($default, $options); if (!is_null($default['customCharacterSet'])) { $this->addCharacterSet('custom', $default['customCharacterSet']); $default['characterSet'] = 'custom'; } $this->scale = $default['scale']; $this->characters = $this->characterSet[$default['characterSet']]; $this->charCount = strlen($this->characters); $this->luminanceStrategy = $default['luminanceStrategy']; return $this; } public function createFromFile($filename) { $img = imagecreatefromstring(file_get_contents($filename)); list($width, $height) = getimagesize($filename); $ascii = null; $incY = $this->scale; $incX = $this->scale / 2; for ($y = 0; $y < $height - 1; $y += $incY) { for ($x = 0; $x < $width - 1; $x += $incX) { $toX = min($x + $this->scale / 2, $width - 1); $toY = min($y + $this->scale, $height - 1); $luminance = $this->luminanceAreaAverage($img, $x, $y, $toX, $toY); $ascii .= $this->luminance2character($luminance); } $ascii .= PHP_EOL; } return $ascii; } public function luminanceAreaAverage($img, $x1, $y1, $x2, $y2) { $numPixels = ($x2 - $x1 + 1) * ($y2 - $y1 + 1); $luminance = 0; for ($x = $x1; $x <= $x2; $x++) { for ($y = $y1; $y <= $y2; $y++) { $rgb = imagecolorat($img, $x, $y); $red = (($rgb >> 16) & 0xFF); $green = (($rgb >> 8) & 0xFF); $blue = ($rgb & 0xFF); $luminance += $this->getLuminance($red, $green, $blue); } } return $luminance / $numPixels; } public function getLuminance($red, $green, $blue) { switch ($this->luminanceStrategy) { case 1: $luminance = ($red * 0.2126 + $green * 0.7152 + $blue * 0.0722) / 255; break; case 2: $luminance = ($red * 0.299 + $green * 0.587 + $blue * 0.114) / 255; break; case 3: $luminance = sqrt(0.299 * pow($red, 2) + 0.587 * pow($green, 2) + 0.114 * pow($blue, 2)) / 255; break; case 0: default: $luminance = ($red + $green + $blue) / (255 * 3); } return $luminance; } public function luminance2character($luminance) { $position = (int) round($luminance * ($this->charCount - 1)); $char = $this->characters[$position]; return $char; } } class CImage { const PNG_GREYSCALE = 0; const PNG_RGB = 2; const PNG_RGB_PALETTE = 3; const PNG_GREYSCALE_ALPHA = 4; const PNG_RGB_ALPHA = 6; const JPEG_QUALITY_DEFAULT = 60; private $quality; private $useQuality = false; const PNG_COMPRESSION_DEFAULT = -1; private $compress; private $useCompress = false; private $HTTPHeader = array(); private $bgColorDefault = array( 'red' => 0, 'green' => 0, 'blue' => 0, 'alpha' => null, ); private $bgColor; private $saveFolder; private $image; private $imageSrc; private $pathToImage; private $fileType; private $extension; private $outputFormat = null; private $lossy = null; private $verbose = false; private $log = array(); private $palette; private $cacheFileName; private $saveAs; private $pngLossy; private $pngLossyCmd; private $pngFilter; private $pngFilterCmd; private $pngDeflate; private $pngDeflateCmd; private $jpegOptimize; private $jpegOptimizeCmd; private $width; private $height; private $newWidth; private $newWidthOrig; private $newHeight; private $newHeightOrig; private $dpr = 1; const UPSCALE_DEFAULT = true; private $upscale = self::UPSCALE_DEFAULT; public $crop; public $cropOrig; private $convolve; private $convolves = array( 'lighten' => '0,0,0, 0,12,0, 0,0,0, 9, 0', 'darken' => '0,0,0, 0,6,0, 0,0,0, 9, 0', 'sharpen' => '-1,-1,-1, -1,16,-1, -1,-1,-1, 8, 0', 'sharpen-alt' => '0,-1,0, -1,5,-1, 0,-1,0, 1, 0', 'emboss' => '1,1,-1, 1,3,-1, 1,-1,-1, 3, 0', 'emboss-alt' => '-2,-1,0, -1,1,1, 0,1,2, 1, 0', 'blur' => '1,1,1, 1,15,1, 1,1,1, 23, 0', 'gblur' => '1,2,1, 2,4,2, 1,2,1, 16, 0', 'edge' => '-1,-1,-1, -1,8,-1, -1,-1,-1, 9, 0', 'edge-alt' => '0,1,0, 1,-4,1, 0,1,0, 1, 0', 'draw' => '0,-1,0, -1,5,-1, 0,-1,0, 0, 0', 'mean' => '1,1,1, 1,1,1, 1,1,1, 9, 0', 'motion' => '1,0,0, 0,1,0, 0,0,1, 3, 0', ); private $fillToFit; private $scale; private $rotateBefore; private $rotateAfter; private $autoRotate; private $sharpen; private $emboss; private $blur; private $offset; private $fillWidth; private $fillHeight; private $allowRemote = false; private $remoteCache; private $remotePattern = '#^https?://#'; private $useCache = true; private $fastTrackCache = null; private $remoteHostWhitelist = null; private $verboseFileName = null; private $asciiOptions = array(); private $interlace = false; const RESIZE = 1; const RESAMPLE = 2; private $copyStrategy = NULL; public $keepRatio; public $cropToFit; private $cropWidth; private $cropHeight; public $crop_x; public $crop_y; public $filters; private $attr; public function __construct($imageSrc = null, $imageFolder = null, $saveFolder = null, $saveName = null) { $this->setSource($imageSrc, $imageFolder); $this->setTarget($saveFolder, $saveName); } public function injectDependency($property, $object) { if (!property_exists($this, $property)) { $this->raiseError("Injecting unknown property."); } $this->$property = $object; return $this; } public function setVerbose($mode = true) { $this->verbose = $mode; return $this; } public function setSaveFolder($path) { $this->saveFolder = $path; return $this; } public function useCache($use = true) { $this->useCache = $use; return $this; } public function createDummyImage($width = null, $height = null) { $this->newWidth = $this->newWidth ?: $width ?: 100; $this->newHeight = $this->newHeight ?: $height ?: 100; $this->image = $this->CreateImageKeepTransparency($this->newWidth, $this->newHeight); return $this; } public function setRemoteDownload($allow, $cache, $pattern = null) { $this->allowRemote = $allow; $this->remoteCache = $cache; $this->remotePattern = is_null($pattern) ? $this->remotePattern : $pattern; $this->log( "Set remote download to: " . ($this->allowRemote ? "true" : "false") . " using pattern " . $this->remotePattern ); return $this; } public function isRemoteSource($src) { $remote = preg_match($this->remotePattern, $src); $this->log("Detected remote image: " . ($remote ? "true" : "false")); return !!$remote; } public function setRemoteHostWhitelist($whitelist = null) { $this->remoteHostWhitelist = $whitelist; $this->log( "Setting remote host whitelist to: " . (is_null($whitelist) ? "null" : print_r($whitelist, 1)) ); return $this; } public function isRemoteSourceOnWhitelist($src) { if (is_null($this->remoteHostWhitelist)) { $this->log("Remote host on whitelist not configured - allowing."); return true; } $whitelist = new CWhitelist(); $hostname = parse_url($src, PHP_URL_HOST); $allow = $whitelist->check($hostname, $this->remoteHostWhitelist); $this->log( "Remote host is on whitelist: " . ($allow ? "true" : "false") ); return $allow; } private function checkFileExtension($extension) { $valid = array('jpg', 'jpeg', 'png', 'gif', 'webp'); in_array(strtolower($extension), $valid) or $this->raiseError('Not a valid file extension.'); return $this; } private function normalizeFileExtension($extension = null) { $extension = strtolower($extension ? $extension : $this->extension); if ($extension == 'jpeg') { $extension = 'jpg'; } return $extension; } public function downloadRemoteSource($src) { if (!$this->isRemoteSourceOnWhitelist($src)) { throw new Exception("Hostname is not on whitelist for remote sources."); } $remote = new CRemoteImage(); if (!is_writable($this->remoteCache)) { $this->log("The remote cache is not writable."); } $remote->setCache($this->remoteCache); $remote->useCache($this->useCache); $src = $remote->download($src); $this->log("Remote HTTP status: " . $remote->getStatus()); $this->log("Remote item is in local cache: $src"); $this->log("Remote details on cache:" . print_r($remote->getDetails(), true)); return $src; } public function setSource($src, $dir = null) { if (!isset($src)) { $this->imageSrc = null; $this->pathToImage = null; return $this; } if ($this->allowRemote && $this->isRemoteSource($src)) { $src = $this->downloadRemoteSource($src); $dir = null; } if (!isset($dir)) { $dir = dirname($src); $src = basename($src); } $this->imageSrc = ltrim($src, '/'); $imageFolder = rtrim($dir, '/'); $this->pathToImage = $imageFolder . '/' . $this->imageSrc; return $this; } public function setTarget($src = null, $dir = null) { if (!isset($src)) { $this->cacheFileName = null; return $this; } if (isset($dir)) { $this->saveFolder = rtrim($dir, '/'); } $this->cacheFileName = $this->saveFolder . '/' . $src; $this->cacheFileName = preg_replace('/^a-zA-Z0-9\.-_/', '', $this->cacheFileName); $this->log("The cache file name is: " . $this->cacheFileName); return $this; } public function getTarget() { return $this->cacheFileName; } public function setOptions($args) { $this->log("Set new options for processing image."); $defaults = array( 'newWidth' => null, 'newHeight' => null, 'aspectRatio' => null, 'keepRatio' => true, 'cropToFit' => false, 'fillToFit' => null, 'crop' => null, 'area' => null, 'upscale' => self::UPSCALE_DEFAULT, 'useCache' => true, 'useOriginal' => true, 'scale' => null, 'rotateBefore' => null, 'autoRotate' => false, 'bgColor' => null, 'palette' => null, 'filters' => null, 'sharpen' => null, 'emboss' => null, 'blur' => null, 'convolve' => null, 'rotateAfter' => null, 'interlace' => null, 'outputFormat' => null, 'dpr' => 1, 'lossy' => null, ); if (isset($args['crop']) && !is_array($args['crop'])) { $pices = explode(',', $args['crop']); $args['crop'] = array( 'width' => $pices[0], 'height' => $pices[1], 'start_x' => $pices[2], 'start_y' => $pices[3], ); } if (isset($args['area']) && !is_array($args['area'])) { $pices = explode(',', $args['area']); $args['area'] = array( 'top' => $pices[0], 'right' => $pices[1], 'bottom' => $pices[2], 'left' => $pices[3], ); } if (isset($args['filters']) && is_array($args['filters'])) { foreach ($args['filters'] as $key => $filterStr) { $parts = explode(',', $filterStr); $filter = $this->mapFilter($parts[0]); $filter['str'] = $filterStr; for ($i=1; $i<=$filter['argc']; $i++) { if (isset($parts[$i])) { $filter["arg{$i}"] = $parts[$i]; } else { throw new Exception( 'Missing arg to filter, review how many arguments are needed at + define("CIMAGE_BUNDLE", true); $config = array( 'mode' => 'strict', ); define("CIMAGE_VERSION", "v0.8.2 (2021-10-27)"); define("CIMAGE_USER_AGENT", "CImage/" . CIMAGE_VERSION); if (!defined("IMG_WEBP")) { define("IMG_WEBP", -1); } function trace($msg) { $file = CIMAGE_DEBUG_FILE; if (!is_writable($file)) { return; } $timer = number_format((microtime(true) - $_SERVER["REQUEST_TIME_FLOAT"]), 6); $details = "{$timer}ms"; $details .= ":" . round(memory_get_peak_usage()/1024/1024, 3) . "MB"; $details .= ":" . count(get_included_files()); file_put_contents($file, "$details:$msg\n", FILE_APPEND); } function errorPage($msg, $type = 500) { global $mode; switch ($type) { case 403: $header = "403 Forbidden"; break; case 404: $header = "404 Not Found"; break; default: $header = "500 Internal Server Error"; } if ($mode == "strict") { $header = "404 Not Found"; } header("HTTP/1.0 $header"); if ($mode == "development") { die("[img.php] $msg"); } error_log("[img.php] $msg"); die("HTTP/1.0 $header"); } function get($key, $default = null) { if (is_array($key)) { foreach ($key as $val) { if (isset($_GET[$val])) { return $_GET[$val]; } } } elseif (isset($_GET[$key])) { return $_GET[$key]; } return $default; } function getDefined($key, $defined, $undefined) { return get($key) === null ? $undefined : $defined; } function getValue($key, $undefined) { $val = get($key); if (is_null($val) || $val === "") { return $undefined; } return $val; } function getConfig($key, $default) { global $config; return isset($config[$key]) ? $config[$key] : $default; } function verbose($msg = null, $arg = "") { global $verbose, $verboseFile; static $log = array(); if (!($verbose || $verboseFile)) { return; } if (is_null($msg)) { return $log; } if (is_null($arg)) { $arg = "null"; } elseif ($arg === false) { $arg = "false"; } elseif ($arg === true) { $arg = "true"; } $log[] = $msg . $arg; } function checkExternalCommand($what, $enabled, $commandString) { $no = $enabled ? null : 'NOT'; $text = "Post processing $what is $no enabled.
"; list($command) = explode(" ", $commandString); $no = is_executable($command) ? null : 'NOT'; $text .= "The command for $what is $no an executable.
"; return $text; } class CHttpGet { private $request = array(); private $response = array(); public function __construct() { $this->request['header'] = array(); } public function buildUrl($baseUrl, $merge) { $parts = parse_url($baseUrl); $parts = array_merge($parts, $merge); $url = $parts['scheme']; $url .= "://"; $url .= $parts['host']; $url .= isset($parts['port']) ? ":" . $parts['port'] : "" ; $url .= $parts['path']; return $url; } public function setUrl($url) { $parts = parse_url($url); $path = ""; if (isset($parts['path'])) { $pathParts = explode('/', $parts['path']); unset($pathParts[0]); foreach ($pathParts as $value) { $path .= "/" . rawurlencode($value); } } $url = $this->buildUrl($url, array("path" => $path)); $this->request['url'] = $url; return $this; } public function setHeader($field, $value) { $this->request['header'][] = "$field: $value"; return $this; } public function parseHeader() { $rawHeaders = rtrim($this->response['headerRaw'], "\r\n"); $headerGroups = explode("\r\n\r\n", $rawHeaders); $header = explode("\r\n", end($headerGroups)); $output = array(); if ('HTTP' === substr($header[0], 0, 4)) { list($output['version'], $output['status']) = explode(' ', $header[0]); unset($header[0]); } foreach ($header as $entry) { $pos = strpos($entry, ':'); $output[trim(substr($entry, 0, $pos))] = trim(substr($entry, $pos + 1)); } $this->response['header'] = $output; return $this; } public function doGet($debug = false) { $options = array( CURLOPT_URL => $this->request['url'], CURLOPT_HEADER => 1, CURLOPT_HTTPHEADER => $this->request['header'], CURLOPT_AUTOREFERER => true, CURLOPT_RETURNTRANSFER => true, CURLINFO_HEADER_OUT => $debug, CURLOPT_CONNECTTIMEOUT => 5, CURLOPT_TIMEOUT => 5, CURLOPT_FOLLOWLOCATION => true, CURLOPT_MAXREDIRS => 2, ); $ch = curl_init(); curl_setopt_array($ch, $options); $response = curl_exec($ch); if (!$response) { throw new Exception("Failed retrieving url, details follows: " . curl_error($ch)); } $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE); $this->response['headerRaw'] = substr($response, 0, $headerSize); $this->response['body'] = substr($response, $headerSize); $this->parseHeader(); if ($debug) { $info = curl_getinfo($ch); echo "Request header
", var_dump($info['request_header']), "
"; echo "Response header (raw)
", var_dump($this->response['headerRaw']), "
"; echo "Response header (parsed)
", var_dump($this->response['header']), "
"; } curl_close($ch); return true; } public function getStatus() { return isset($this->response['header']['status']) ? (int) $this->response['header']['status'] : null; } public function getLastModified() { return isset($this->response['header']['Last-Modified']) ? strtotime($this->response['header']['Last-Modified']) : null; } public function getContentType() { $type = isset($this->response['header']['Content-Type']) ? $this->response['header']['Content-Type'] : null; return preg_match('#[a-z]+/[a-z]+#', $type) ? $type : null; } public function getDate($default = false) { return isset($this->response['header']['Date']) ? strtotime($this->response['header']['Date']) : $default; } public function getMaxAge($default = false) { $cacheControl = isset($this->response['header']['Cache-Control']) ? $this->response['header']['Cache-Control'] : null; $maxAge = null; if ($cacheControl) { $part = explode('=', $cacheControl); $maxAge = ($part[0] == "max-age") ? (int) $part[1] : null; } if ($maxAge) { return $maxAge; } $expire = isset($this->response['header']['Expires']) ? strtotime($this->response['header']['Expires']) : null; return $expire ? $expire : $default; } public function getBody() { return $this->response['body']; } } class CRemoteImage { private $saveFolder = null; private $useCache = true; private $http; private $status; private $defaultMaxAge = 604800; private $url; private $fileName; private $fileJson; private $cache; public function getStatus() { return $this->status; } public function getDetails() { return $this->cache; } public function setCache($path) { $this->saveFolder = rtrim($path, "/") . "/"; return $this; } public function isCacheWritable() { if (!is_writable($this->saveFolder)) { throw new Exception("Cache folder is not writable for downloaded files."); } return $this; } public function useCache($use = true) { $this->useCache = $use; return $this; } public function setHeaderFields() { $cimageVersion = "CImage"; if (defined("CIMAGE_USER_AGENT")) { $cimageVersion = CIMAGE_USER_AGENT; } $this->http->setHeader("User-Agent", "$cimageVersion (PHP/". phpversion() . " cURL)"); $this->http->setHeader("Accept", "image/jpeg,image/png,image/gif"); if ($this->useCache) { $this->http->setHeader("Cache-Control", "max-age=0"); } else { $this->http->setHeader("Cache-Control", "no-cache"); $this->http->setHeader("Pragma", "no-cache"); } } public function save() { $this->cache = array(); $date = $this->http->getDate(time()); $maxAge = $this->http->getMaxAge($this->defaultMaxAge); $lastModified = $this->http->getLastModified(); $type = $this->http->getContentType(); $this->cache['Date'] = gmdate("D, d M Y H:i:s T", $date); $this->cache['Max-Age'] = $maxAge; $this->cache['Content-Type'] = $type; $this->cache['Url'] = $this->url; if ($lastModified) { $this->cache['Last-Modified'] = gmdate("D, d M Y H:i:s T", $lastModified); } $body = $this->http->getBody(); $img = imagecreatefromstring($body); if ($img !== false) { file_put_contents($this->fileName, $body); file_put_contents($this->fileJson, json_encode($this->cache)); return $this->fileName; } return false; } public function updateCacheDetails() { $date = $this->http->getDate(time()); $maxAge = $this->http->getMaxAge($this->defaultMaxAge); $lastModified = $this->http->getLastModified(); $this->cache['Date'] = gmdate("D, d M Y H:i:s T", $date); $this->cache['Max-Age'] = $maxAge; if ($lastModified) { $this->cache['Last-Modified'] = gmdate("D, d M Y H:i:s T", $lastModified); } file_put_contents($this->fileJson, json_encode($this->cache)); return $this->fileName; } public function download($url) { $this->http = new CHttpGet(); $this->url = $url; $this->loadCacheDetails(); if ($this->useCache) { $src = $this->getCachedSource(); if ($src) { $this->status = 1; return $src; } } $this->setHeaderFields(); $this->http->setUrl($this->url); $this->http->doGet(); $this->status = $this->http->getStatus(); if ($this->status === 200) { $this->isCacheWritable(); return $this->save(); } elseif ($this->status === 304) { $this->isCacheWritable(); return $this->updateCacheDetails(); } throw new Exception("Unknown statuscode when downloading remote image: " . $this->status); } public function loadCacheDetails() { $cacheFile = md5($this->url); $this->fileName = $this->saveFolder . $cacheFile; $this->fileJson = $this->fileName . ".json"; if (is_readable($this->fileJson)) { $this->cache = json_decode(file_get_contents($this->fileJson), true); } } public function getCachedSource() { $imageExists = is_readable($this->fileName); $date = strtotime($this->cache['Date']); $maxAge = $this->cache['Max-Age']; $now = time(); if ($imageExists && $date + $maxAge > $now) { return $this->fileName; } if ($imageExists && isset($this->cache['Last-Modified'])) { $this->http->setHeader("If-Modified-Since", $this->cache['Last-Modified']); } return false; } } class CWhitelist { private $whitelist = array(); public function set($whitelist = array()) { if (!is_array($whitelist)) { throw new Exception("Whitelist is not of a supported format."); } $this->whitelist = $whitelist; return $this; } public function check($item, $whitelist = null) { if ($whitelist !== null) { $this->set($whitelist); } if (empty($item) or empty($this->whitelist)) { return false; } foreach ($this->whitelist as $regexp) { if (preg_match("#$regexp#", $item)) { return true; } } return false; } } class CAsciiArt { private $characterSet = array( 'one' => "#0XT|:,.' ", 'two' => "@%#*+=-:. ", 'three' => "$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. " ); private $characters = null; private $charCount = null; private $scale = null; private $luminanceStrategy = null; public function __construct() { $this->setOptions(); } public function addCharacterSet($key, $value) { $this->characterSet[$key] = $value; return $this; } public function setOptions($options = array()) { $default = array( "characterSet" => 'two', "scale" => 14, "luminanceStrategy" => 3, "customCharacterSet" => null, ); $default = array_merge($default, $options); if (!is_null($default['customCharacterSet'])) { $this->addCharacterSet('custom', $default['customCharacterSet']); $default['characterSet'] = 'custom'; } $this->scale = $default['scale']; $this->characters = $this->characterSet[$default['characterSet']]; $this->charCount = strlen($this->characters); $this->luminanceStrategy = $default['luminanceStrategy']; return $this; } public function createFromFile($filename) { $img = imagecreatefromstring(file_get_contents($filename)); list($width, $height) = getimagesize($filename); $ascii = null; $incY = $this->scale; $incX = $this->scale / 2; for ($y = 0; $y < $height - 1; $y += $incY) { for ($x = 0; $x < $width - 1; $x += $incX) { $toX = min($x + $this->scale / 2, $width - 1); $toY = min($y + $this->scale, $height - 1); $luminance = $this->luminanceAreaAverage($img, $x, $y, $toX, $toY); $ascii .= $this->luminance2character($luminance); } $ascii .= PHP_EOL; } return $ascii; } public function luminanceAreaAverage($img, $x1, $y1, $x2, $y2) { $numPixels = ($x2 - $x1 + 1) * ($y2 - $y1 + 1); $luminance = 0; for ($x = $x1; $x <= $x2; $x++) { for ($y = $y1; $y <= $y2; $y++) { $rgb = imagecolorat($img, $x, $y); $red = (($rgb >> 16) & 0xFF); $green = (($rgb >> 8) & 0xFF); $blue = ($rgb & 0xFF); $luminance += $this->getLuminance($red, $green, $blue); } } return $luminance / $numPixels; } public function getLuminance($red, $green, $blue) { switch ($this->luminanceStrategy) { case 1: $luminance = ($red * 0.2126 + $green * 0.7152 + $blue * 0.0722) / 255; break; case 2: $luminance = ($red * 0.299 + $green * 0.587 + $blue * 0.114) / 255; break; case 3: $luminance = sqrt(0.299 * pow($red, 2) + 0.587 * pow($green, 2) + 0.114 * pow($blue, 2)) / 255; break; case 0: default: $luminance = ($red + $green + $blue) / (255 * 3); } return $luminance; } public function luminance2character($luminance) { $position = (int) round($luminance * ($this->charCount - 1)); $char = $this->characters[$position]; return $char; } } class CImage { const PNG_GREYSCALE = 0; const PNG_RGB = 2; const PNG_RGB_PALETTE = 3; const PNG_GREYSCALE_ALPHA = 4; const PNG_RGB_ALPHA = 6; const JPEG_QUALITY_DEFAULT = 60; private $quality; private $useQuality = false; const PNG_COMPRESSION_DEFAULT = -1; private $compress; private $useCompress = false; private $HTTPHeader = array(); private $bgColorDefault = array( 'red' => 0, 'green' => 0, 'blue' => 0, 'alpha' => null, ); private $bgColor; private $saveFolder; private $image; private $imageSrc; private $pathToImage; private $fileType; private $extension; private $outputFormat = null; private $lossy = null; private $verbose = false; private $log = array(); private $palette; private $cacheFileName; private $saveAs; private $pngLossy; private $pngLossyCmd; private $pngFilter; private $pngFilterCmd; private $pngDeflate; private $pngDeflateCmd; private $jpegOptimize; private $jpegOptimizeCmd; private $width; private $height; private $newWidth; private $newWidthOrig; private $newHeight; private $newHeightOrig; private $dpr = 1; const UPSCALE_DEFAULT = true; private $upscale = self::UPSCALE_DEFAULT; public $crop; public $cropOrig; private $convolve; private $convolves = array( 'lighten' => '0,0,0, 0,12,0, 0,0,0, 9, 0', 'darken' => '0,0,0, 0,6,0, 0,0,0, 9, 0', 'sharpen' => '-1,-1,-1, -1,16,-1, -1,-1,-1, 8, 0', 'sharpen-alt' => '0,-1,0, -1,5,-1, 0,-1,0, 1, 0', 'emboss' => '1,1,-1, 1,3,-1, 1,-1,-1, 3, 0', 'emboss-alt' => '-2,-1,0, -1,1,1, 0,1,2, 1, 0', 'blur' => '1,1,1, 1,15,1, 1,1,1, 23, 0', 'gblur' => '1,2,1, 2,4,2, 1,2,1, 16, 0', 'edge' => '-1,-1,-1, -1,8,-1, -1,-1,-1, 9, 0', 'edge-alt' => '0,1,0, 1,-4,1, 0,1,0, 1, 0', 'draw' => '0,-1,0, -1,5,-1, 0,-1,0, 0, 0', 'mean' => '1,1,1, 1,1,1, 1,1,1, 9, 0', 'motion' => '1,0,0, 0,1,0, 0,0,1, 3, 0', ); private $fillToFit; private $scale; private $rotateBefore; private $rotateAfter; private $autoRotate; private $sharpen; private $emboss; private $blur; private $offset; private $fillWidth; private $fillHeight; private $allowRemote = false; private $remoteCache; private $remotePattern = '#^https?://#'; private $useCache = true; private $fastTrackCache = null; private $remoteHostWhitelist = null; private $verboseFileName = null; private $asciiOptions = array(); private $interlace = false; const RESIZE = 1; const RESAMPLE = 2; private $copyStrategy = NULL; public $keepRatio; public $cropToFit; private $cropWidth; private $cropHeight; public $crop_x; public $crop_y; public $filters; private $attr; public function __construct($imageSrc = null, $imageFolder = null, $saveFolder = null, $saveName = null) { $this->setSource($imageSrc, $imageFolder); $this->setTarget($saveFolder, $saveName); } public function injectDependency($property, $object) { if (!property_exists($this, $property)) { $this->raiseError("Injecting unknown property."); } $this->$property = $object; return $this; } public function setVerbose($mode = true) { $this->verbose = $mode; return $this; } public function setSaveFolder($path) { $this->saveFolder = $path; return $this; } public function useCache($use = true) { $this->useCache = $use; return $this; } public function createDummyImage($width = null, $height = null) { $this->newWidth = $this->newWidth ?: $width ?: 100; $this->newHeight = $this->newHeight ?: $height ?: 100; $this->image = $this->CreateImageKeepTransparency($this->newWidth, $this->newHeight); return $this; } public function setRemoteDownload($allow, $cache, $pattern = null) { $this->allowRemote = $allow; $this->remoteCache = $cache; $this->remotePattern = is_null($pattern) ? $this->remotePattern : $pattern; $this->log( "Set remote download to: " . ($this->allowRemote ? "true" : "false") . " using pattern " . $this->remotePattern ); return $this; } public function isRemoteSource($src) { $remote = preg_match($this->remotePattern, $src); $this->log("Detected remote image: " . ($remote ? "true" : "false")); return !!$remote; } public function setRemoteHostWhitelist($whitelist = null) { $this->remoteHostWhitelist = $whitelist; $this->log( "Setting remote host whitelist to: " . (is_null($whitelist) ? "null" : print_r($whitelist, 1)) ); return $this; } public function isRemoteSourceOnWhitelist($src) { if (is_null($this->remoteHostWhitelist)) { $this->log("Remote host on whitelist not configured - allowing."); return true; } $whitelist = new CWhitelist(); $hostname = parse_url($src, PHP_URL_HOST); $allow = $whitelist->check($hostname, $this->remoteHostWhitelist); $this->log( "Remote host is on whitelist: " . ($allow ? "true" : "false") ); return $allow; } private function checkFileExtension($extension) { $valid = array('jpg', 'jpeg', 'png', 'gif', 'webp'); in_array(strtolower($extension), $valid) or $this->raiseError('Not a valid file extension.'); return $this; } private function normalizeFileExtension($extension = null) { $extension = strtolower($extension ? $extension : $this->extension); if ($extension == 'jpeg') { $extension = 'jpg'; } return $extension; } public function downloadRemoteSource($src) { if (!$this->isRemoteSourceOnWhitelist($src)) { throw new Exception("Hostname is not on whitelist for remote sources."); } $remote = new CRemoteImage(); if (!is_writable($this->remoteCache)) { $this->log("The remote cache is not writable."); } $remote->setCache($this->remoteCache); $remote->useCache($this->useCache); $src = $remote->download($src); $this->log("Remote HTTP status: " . $remote->getStatus()); $this->log("Remote item is in local cache: $src"); $this->log("Remote details on cache:" . print_r($remote->getDetails(), true)); return $src; } public function setSource($src, $dir = null) { if (!isset($src)) { $this->imageSrc = null; $this->pathToImage = null; return $this; } if ($this->allowRemote && $this->isRemoteSource($src)) { $src = $this->downloadRemoteSource($src); $dir = null; } if (!isset($dir)) { $dir = dirname($src); $src = basename($src); } $this->imageSrc = ltrim($src, '/'); $imageFolder = rtrim($dir, '/'); $this->pathToImage = $imageFolder . '/' . $this->imageSrc; return $this; } public function setTarget($src = null, $dir = null) { if (!isset($src)) { $this->cacheFileName = null; return $this; } if (isset($dir)) { $this->saveFolder = rtrim($dir, '/'); } $this->cacheFileName = $this->saveFolder . '/' . $src; $this->cacheFileName = preg_replace('/^a-zA-Z0-9\.-_/', '', $this->cacheFileName); $this->log("The cache file name is: " . $this->cacheFileName); return $this; } public function getTarget() { return $this->cacheFileName; } public function setOptions($args) { $this->log("Set new options for processing image."); $defaults = array( 'newWidth' => null, 'newHeight' => null, 'aspectRatio' => null, 'keepRatio' => true, 'cropToFit' => false, 'fillToFit' => null, 'crop' => null, 'area' => null, 'upscale' => self::UPSCALE_DEFAULT, 'useCache' => true, 'useOriginal' => true, 'scale' => null, 'rotateBefore' => null, 'autoRotate' => false, 'bgColor' => null, 'palette' => null, 'filters' => null, 'sharpen' => null, 'emboss' => null, 'blur' => null, 'convolve' => null, 'rotateAfter' => null, 'interlace' => null, 'outputFormat' => null, 'dpr' => 1, 'lossy' => null, ); if (isset($args['crop']) && !is_array($args['crop'])) { $pices = explode(',', $args['crop']); $args['crop'] = array( 'width' => $pices[0], 'height' => $pices[1], 'start_x' => $pices[2], 'start_y' => $pices[3], ); } if (isset($args['area']) && !is_array($args['area'])) { $pices = explode(',', $args['area']); $args['area'] = array( 'top' => $pices[0], 'right' => $pices[1], 'bottom' => $pices[2], 'left' => $pices[3], ); } if (isset($args['filters']) && is_array($args['filters'])) { foreach ($args['filters'] as $key => $filterStr) { $parts = explode(',', $filterStr); $filter = $this->mapFilter($parts[0]); $filter['str'] = $filterStr; for ($i=1; $i<=$filter['argc']; $i++) { if (isset($parts[$i])) { $filter["arg{$i}"] = $parts[$i]; } else { throw new Exception( 'Missing arg to filter, review how many arguments are needed at http://php.net/manual/en/function.imagefilter.php' ); } } $args['filters'][$key] = $filter; } } $args = array_merge($defaults, $args); foreach ($defaults as $key => $val) { $this->{$key} = $args[$key]; } if ($this->bgColor) { $this->setDefaultBackgroundColor($this->bgColor); } $this->newWidthOrig = $this->newWidth; $this->newHeightOrig = $this->newHeight; $this->cropOrig = $this->crop; return $this; } private function mapFilter($name) { $map = array( 'negate' => array('id'=>0, 'argc'=>0, 'type'=>IMG_FILTER_NEGATE), 'grayscale' => array('id'=>1, 'argc'=>0, 'type'=>IMG_FILTER_GRAYSCALE), 'brightness' => array('id'=>2, 'argc'=>1, 'type'=>IMG_FILTER_BRIGHTNESS), 'contrast' => array('id'=>3, 'argc'=>1, 'type'=>IMG_FILTER_CONTRAST), 'colorize' => array('id'=>4, 'argc'=>4, 'type'=>IMG_FILTER_COLORIZE), 'edgedetect' => array('id'=>5, 'argc'=>0, 'type'=>IMG_FILTER_EDGEDETECT), 'emboss' => array('id'=>6, 'argc'=>0, 'type'=>IMG_FILTER_EMBOSS), 'gaussian_blur' => array('id'=>7, 'argc'=>0, 'type'=>IMG_FILTER_GAUSSIAN_BLUR), 'selective_blur' => array('id'=>8, 'argc'=>0, 'type'=>IMG_FILTER_SELECTIVE_BLUR), 'mean_removal' => array('id'=>9, 'argc'=>0, 'type'=>IMG_FILTER_MEAN_REMOVAL), 'smooth' => array('id'=>10, 'argc'=>1, 'type'=>IMG_FILTER_SMOOTH), 'pixelate' => array('id'=>11, 'argc'=>2, 'type'=>IMG_FILTER_PIXELATE), ); if (isset($map[$name])) { return $map[$name]; } else { throw new Exception('No such filter.'); } } public function loadImageDetails($file = null) { $file = $file ? $file : $this->pathToImage; is_readable($file) or $this->raiseError('Image file does not exist.'); $info = list($this->width, $this->height, $this->fileType) = getimagesize($file); if (empty($info)) { $this->fileType = false; if (function_exists("exif_imagetype")) { $this->fileType = exif_imagetype($file); if ($this->fileType === false) { if (function_exists("imagecreatefromwebp")) { $webp = imagecreatefromwebp($file); if ($webp !== false) { $this->width = imagesx($webp); $this->height = imagesy($webp); $this->fileType = IMG_WEBP; } } } } } if (!$this->fileType) { throw new Exception("Loading image details, the file doesn't seem to be a valid image."); } if ($this->verbose) { $this->log("Loading image details for: {$file}"); $this->log(" Image width x height (type): {$this->width} x {$this->height} ({$this->fileType})."); $this->log(" Image filesize: " . filesize($file) . " bytes."); $this->log(" Image mimetype: " . $this->getMimeType()); } return $this; } protected function getMimeType() { if ($this->fileType === IMG_WEBP) { return "image/webp"; } return image_type_to_mime_type($this->fileType); } public function initDimensions() { $this->log("Init dimension (before) newWidth x newHeight is {$this->newWidth} x {$this->newHeight}."); if ($this->newWidth && $this->newWidth[strlen($this->newWidth)-1] == '%') { $this->newWidth = $this->width * substr($this->newWidth, 0, -1) / 100; $this->log("Setting new width based on % to {$this->newWidth}"); } if ($this->newHeight && $this->newHeight[strlen($this->newHeight)-1] == '%') { $this->newHeight = $this->height * substr($this->newHeight, 0, -1) / 100; $this->log("Setting new height based on % to {$this->newHeight}"); } is_null($this->aspectRatio) or is_numeric($this->aspectRatio) or $this->raiseError('Aspect ratio out of range'); if ($this->aspectRatio && is_null($this->newWidth) && is_null($this->newHeight)) { if ($this->aspectRatio >= 1) { $this->newWidth = $this->width; $this->newHeight = $this->width / $this->aspectRatio; $this->log("Setting new width & height based on width & aspect ratio (>=1) to (w x h) {$this->newWidth} x {$this->newHeight}"); } else { $this->newHeight = $this->height; $this->newWidth = $this->height * $this->aspectRatio; $this->log("Setting new width & height based on width & aspect ratio (<1) to (w x h) {$this->newWidth} x {$this->newHeight}"); } } elseif ($this->aspectRatio && is_null($this->newWidth)) { $this->newWidth = $this->newHeight * $this->aspectRatio; $this->log("Setting new width based on aspect ratio to {$this->newWidth}"); } elseif ($this->aspectRatio && is_null($this->newHeight)) { $this->newHeight = $this->newWidth / $this->aspectRatio; $this->log("Setting new height based on aspect ratio to {$this->newHeight}"); } if ($this->dpr != 1) { if (!is_null($this->newWidth)) { $this->newWidth = round($this->newWidth * $this->dpr); $this->log("Setting new width based on dpr={$this->dpr} - w={$this->newWidth}"); } if (!is_null($this->newHeight)) { $this->newHeight = round($this->newHeight * $this->dpr); $this->log("Setting new height based on dpr={$this->dpr} - h={$this->newHeight}"); } } is_null($this->newWidth) or is_numeric($this->newWidth) or $this->raiseError('Width not numeric'); is_null($this->newHeight) or is_numeric($this->newHeight) or $this->raiseError('Height not numeric'); $this->log("Init dimension (after) newWidth x newHeight is {$this->newWidth} x {$this->newHeight}."); return $this; } public function calculateNewWidthAndHeight() { $this->log("Calculate new width and height."); $this->log("Original width x height is {$this->width} x {$this->height}."); $this->log("Target dimension (before calculating) newWidth x newHeight is {$this->newWidth} x {$this->newHeight}."); if (isset($this->area)) { $this->offset['top'] = round($this->area['top'] / 100 * $this->height); $this->offset['right'] = round($this->area['right'] / 100 * $this->width); $this->offset['bottom'] = round($this->area['bottom'] / 100 * $this->height); $this->offset['left'] = round($this->area['left'] / 100 * $this->width); $this->offset['width'] = $this->width - $this->offset['left'] - $this->offset['right']; $this->offset['height'] = $this->height - $this->offset['top'] - $this->offset['bottom']; $this->width = $this->offset['width']; $this->height = $this->offset['height']; $this->log("The offset for the area to use is top {$this->area['top']}%, right {$this->area['right']}%, bottom {$this->area['bottom']}%, left {$this->area['left']}%."); $this->log("The offset for the area to use is top {$this->offset['top']}px, right {$this->offset['right']}px, bottom {$this->offset['bottom']}px, left {$this->offset['left']}px, width {$this->offset['width']}px, height {$this->offset['height']}px."); } $width = $this->width; $height = $this->height; if ($this->crop) { $width = $this->crop['width'] = $this->crop['width'] <= 0 ? $this->width + $this->crop['width'] : $this->crop['width']; $height = $this->crop['height'] = $this->crop['height'] <= 0 ? $this->height + $this->crop['height'] : $this->crop['height']; if ($this->crop['start_x'] == 'left') { $this->crop['start_x'] = 0; } elseif ($this->crop['start_x'] == 'right') { $this->crop['start_x'] = $this->width - $width; } elseif ($this->crop['start_x'] == 'center') { $this->crop['start_x'] = round($this->width / 2) - round($width / 2); } if ($this->crop['start_y'] == 'top') { $this->crop['start_y'] = 0; } elseif ($this->crop['start_y'] == 'bottom') { $this->crop['start_y'] = $this->height - $height; } elseif ($this->crop['start_y'] == 'center') { $this->crop['start_y'] = round($this->height / 2) - round($height / 2); } $this->log("Crop area is width {$width}px, height {$height}px, start_x {$this->crop['start_x']}px, start_y {$this->crop['start_y']}px."); } if ($this->keepRatio) { $this->log("Keep aspect ratio."); if (($this->cropToFit || $this->fillToFit) && isset($this->newWidth) && isset($this->newHeight)) { $this->log("Use newWidth and newHeigh as width/height, image should fit in box."); } elseif (isset($this->newWidth) && isset($this->newHeight)) { $ratioWidth = $width / $this->newWidth; $ratioHeight = $height / $this->newHeight; $ratio = ($ratioWidth > $ratioHeight) ? $ratioWidth : $ratioHeight; $this->newWidth = round($width / $ratio); $this->newHeight = round($height / $ratio); $this->log("New width and height was set."); } elseif (isset($this->newWidth)) { $factor = (float)$this->newWidth / (float)$width; $this->newHeight = round($factor * $height); $this->log("New width was set."); } elseif (isset($this->newHeight)) { $factor = (float)$this->newHeight / (float)$height; $this->newWidth = round($factor * $width); $this->log("New height was set."); } else { $this->newWidth = $width; $this->newHeight = $height; } if ($this->cropToFit || $this->fillToFit) { $ratioWidth = $width / $this->newWidth; $ratioHeight = $height / $this->newHeight; if ($this->cropToFit) { $this->log("Crop to fit."); $ratio = ($ratioWidth < $ratioHeight) ? $ratioWidth : $ratioHeight; $this->cropWidth = round($width / $ratio); $this->cropHeight = round($height / $ratio); $this->log("Crop width, height, ratio: $this->cropWidth x $this->cropHeight ($ratio)."); } elseif ($this->fillToFit) { $this->log("Fill to fit."); $ratio = ($ratioWidth < $ratioHeight) ? $ratioHeight : $ratioWidth; $this->fillWidth = round($width / $ratio); $this->fillHeight = round($height / $ratio); $this->log("Fill width, height, ratio: $this->fillWidth x $this->fillHeight ($ratio)."); } } } if ($this->crop) { $this->log("Crop."); $this->newWidth = round(isset($this->newWidth) ? $this->newWidth : $this->crop['width']); $this->newHeight = round(isset($this->newHeight) ? $this->newHeight : $this->crop['height']); } $this->newWidth = round(isset($this->newWidth) ? $this->newWidth : $this->width); $this->newHeight = round(isset($this->newHeight) ? $this->newHeight : $this->height); $this->log("Calculated new width x height as {$this->newWidth} x {$this->newHeight}."); return $this; } public function reCalculateDimensions() { $this->log("Re-calculate image dimensions, newWidth x newHeigh was: " . $this->newWidth . " x " . $this->newHeight); $this->newWidth = $this->newWidthOrig; $this->newHeight = $this->newHeightOrig; $this->crop = $this->cropOrig; $this->initDimensions() ->calculateNewWidthAndHeight(); return $this; } public function setSaveAsExtension($saveAs = null) { if (isset($saveAs)) { $saveAs = strtolower($saveAs); $this->checkFileExtension($saveAs); $this->saveAs = $saveAs; $this->extension = $saveAs; } $this->log("Prepare to save image as: " . $this->extension); return $this; } public function setJpegQuality($quality = null) { if ($quality) { $this->useQuality = true; } $this->quality = isset($quality) ? $quality : self::JPEG_QUALITY_DEFAULT; (is_numeric($this->quality) and $this->quality > 0 and $this->quality <= 100) or $this->raiseError('Quality not in range.'); $this->log("Setting JPEG quality to {$this->quality}."); return $this; } public function setPngCompression($compress = null) { if ($compress) { $this->useCompress = true; } $this->compress = isset($compress) ? $compress : self::PNG_COMPRESSION_DEFAULT; (is_numeric($this->compress) and $this->compress >= -1 and $this->compress <= 9) or $this->raiseError('Quality not in range.'); $this->log("Setting PNG compression level to {$this->compress}."); return $this; } public function useOriginalIfPossible($useOrig = true) { if ($useOrig && ($this->newWidth == $this->width) && ($this->newHeight == $this->height) && !$this->area && !$this->crop && !$this->cropToFit && !$this->fillToFit && !$this->filters && !$this->sharpen && !$this->emboss && !$this->blur && !$this->convolve && !$this->palette && !$this->useQuality && !$this->useCompress && !$this->saveAs && !$this->rotateBefore && !$this->rotateAfter && !$this->autoRotate && !$this->bgColor && ($this->upscale === self::UPSCALE_DEFAULT) && !$this->lossy ) { $this->log("Using original image."); $this->output($this->pathToImage); } return $this; } public function generateFilename($base = null, $useSubdir = true, $prefix = null) { $filename = basename($this->pathToImage); $cropToFit = $this->cropToFit ? '_cf' : null; $fillToFit = $this->fillToFit ? '_ff' : null; $crop_x = $this->crop_x ? "_x{$this->crop_x}" : null; $crop_y = $this->crop_y ? "_y{$this->crop_y}" : null; $scale = $this->scale ? "_s{$this->scale}" : null; $bgColor = $this->bgColor ? "_bgc{$this->bgColor}" : null; $quality = $this->quality ? "_q{$this->quality}" : null; $compress = $this->compress ? "_co{$this->compress}" : null; $rotateBefore = $this->rotateBefore ? "_rb{$this->rotateBefore}" : null; $rotateAfter = $this->rotateAfter ? "_ra{$this->rotateAfter}" : null; $lossy = $this->lossy ? "_l" : null; $interlace = $this->interlace ? "_i" : null; $saveAs = $this->normalizeFileExtension(); $saveAs = $saveAs ? "_$saveAs" : null; $copyStrat = null; if ($this->copyStrategy === self::RESIZE) { $copyStrat = "_rs"; } $width = $this->newWidth ? '_' . $this->newWidth : null; $height = $this->newHeight ? '_' . $this->newHeight : null; $offset = isset($this->offset) ? '_o' . $this->offset['top'] . '-' . $this->offset['right'] . '-' . $this->offset['bottom'] . '-' . $this->offset['left'] : null; $crop = $this->crop ? '_c' . $this->crop['width'] . '-' . $this->crop['height'] . '-' . $this->crop['start_x'] . '-' . $this->crop['start_y'] : null; $filters = null; if (isset($this->filters)) { foreach ($this->filters as $filter) { if (is_array($filter)) { $filters .= "_f{$filter['id']}"; for ($i=1; $i<=$filter['argc']; $i++) { $filters .= "-".$filter["arg{$i}"]; } } } } $sharpen = $this->sharpen ? 's' : null; $emboss = $this->emboss ? 'e' : null; $blur = $this->blur ? 'b' : null; $palette = $this->palette ? 'p' : null; $autoRotate = $this->autoRotate ? 'ar' : null; $optimize = $this->jpegOptimize ? 'o' : null; $optimize .= $this->pngFilter ? 'f' : null; $optimize .= $this->pngDeflate ? 'd' : null; $convolve = null; if ($this->convolve) { $convolve = '_conv' . preg_replace('/[^a-zA-Z0-9]/', '', $this->convolve); } $upscale = null; if ($this->upscale !== self::UPSCALE_DEFAULT) { $upscale = '_nu'; } $subdir = null; if ($useSubdir === true) { $subdir = str_replace('/', '-', dirname($this->imageSrc)); $subdir = ($subdir == '.') ? '_.' : $subdir; $subdir .= '_'; } $file = $prefix . $subdir . $filename . $width . $height . $offset . $crop . $cropToFit . $fillToFit . $crop_x . $crop_y . $upscale . $quality . $filters . $sharpen . $emboss . $blur . $palette . $optimize . $compress . $scale . $rotateBefore . $rotateAfter . $autoRotate . $bgColor . $convolve . $copyStrat . $lossy . $interlace . $saveAs; return $this->setTarget($file, $base); } public function useCacheIfPossible($useCache = true) { if ($useCache && is_readable($this->cacheFileName)) { $fileTime = filemtime($this->pathToImage); $cacheTime = filemtime($this->cacheFileName); if ($fileTime <= $cacheTime) { if ($this->useCache) { if ($this->verbose) { $this->log("Use cached file."); $this->log("Cached image filesize: " . filesize($this->cacheFileName) . " bytes."); } $this->output($this->cacheFileName, $this->outputFormat); } else { $this->log("Cache is valid but ignoring it by intention."); } } else { $this->log("Original file is modified, ignoring cache."); } } else { $this->log("Cachefile does not exists or ignoring it."); } return $this; } public function load($src = null, $dir = null) { if (isset($src)) { $this->setSource($src, $dir); } $this->loadImageDetails(); if ($this->fileType === IMG_WEBP) { $this->image = imagecreatefromwebp($this->pathToImage); } else { $imageAsString = file_get_contents($this->pathToImage); $this->image = imagecreatefromstring($imageAsString); } if ($this->image === false) { throw new Exception("Could not load image."); } if ($this->verbose) { $this->log("### Image successfully loaded from file."); $this->log(" imageistruecolor() : " . (imageistruecolor($this->image) ? 'true' : 'false')); $this->log(" imagecolorstotal() : " . imagecolorstotal($this->image)); $this->log(" Number of colors in image = " . $this->colorsTotal($this->image)); $index = imagecolortransparent($this->image); $this->log(" Detected transparent color = " . ($index >= 0 ? implode(", ", imagecolorsforindex($this->image, $index)) : "NONE") . " at index = $index"); } return $this; } public function getPngType($filename = null) { $filename = $filename ? $filename : $this->pathToImage; $pngType = ord(file_get_contents($filename, false, null, 25, 1)); if ($this->verbose) { $this->log("Checking png type of: " . $filename); $this->log($this->getPngTypeAsString($pngType)); } return $pngType; } private function getPngTypeAsString($pngType = null, $filename = null) { if ($filename || !$pngType) { $pngType = $this->getPngType($filename); } $index = imagecolortransparent($this->image); $transparent = null; if ($index != -1) { $transparent = " (transparent)"; } switch ($pngType) { case self::PNG_GREYSCALE: $text = "PNG is type 0, Greyscale$transparent"; break; case self::PNG_RGB: $text = "PNG is type 2, RGB$transparent"; break; case self::PNG_RGB_PALETTE: $text = "PNG is type 3, RGB with palette$transparent"; break; case self::PNG_GREYSCALE_ALPHA: $text = "PNG is type 4, Greyscale with alpha channel"; break; case self::PNG_RGB_ALPHA: $text = "PNG is type 6, RGB with alpha channel (PNG 32-bit)"; break; default: $text = "PNG is UNKNOWN type, is it really a PNG image?"; } return $text; } private function colorsTotal($im) { if (imageistruecolor($im)) { $this->log("Colors as true color."); $h = imagesy($im); $w = imagesx($im); $c = array(); for ($x=0; $x < $w; $x++) { for ($y=0; $y < $h; $y++) { @$c['c'.imagecolorat($im, $x, $y)]++; } } return count($c); } else { $this->log("Colors as palette."); return imagecolorstotal($im); } } public function preResize() { $this->log("### Pre-process before resizing"); if ($this->rotateBefore) { $this->log("Rotating image."); $this->rotate($this->rotateBefore, $this->bgColor) ->reCalculateDimensions(); } if ($this->autoRotate) { $this->log("Auto rotating image."); $this->rotateExif() ->reCalculateDimensions(); } if (isset($this->scale)) { $this->log("Scale by {$this->scale}%"); $newWidth = $this->width * $this->scale / 100; $newHeight = $this->height * $this->scale / 100; $img = $this->CreateImageKeepTransparency($newWidth, $newHeight); imagecopyresampled($img, $this->image, 0, 0, 0, 0, $newWidth, $newHeight, $this->width, $this->height); $this->image = $img; $this->width = $newWidth; $this->height = $newHeight; } return $this; } public function setCopyResizeStrategy($strategy) { $this->copyStrategy = $strategy; return $this; } public function imageCopyResampled($dst_image, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h) { if($this->copyStrategy == self::RESIZE) { $this->log("Copy by resize"); imagecopyresized($dst_image, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h); } else { $this->log("Copy by resample"); imagecopyresampled($dst_image, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h); } } public function resize() { $this->log("### Starting to Resize()"); $this->log("Upscale = '$this->upscale'"); if (isset($this->offset)) { $this->log("Offset for area to use, cropping it width={$this->offset['width']}, height={$this->offset['height']}, start_x={$this->offset['left']}, start_y={$this->offset['top']}"); $img = $this->CreateImageKeepTransparency($this->offset['width'], $this->offset['height']); imagecopy($img, $this->image, 0, 0, $this->offset['left'], $this->offset['top'], $this->offset['width'], $this->offset['height']); $this->image = $img; $this->width = $this->offset['width']; $this->height = $this->offset['height']; } if ($this->crop) { $this->log("Cropping area width={$this->crop['width']}, height={$this->crop['height']}, start_x={$this->crop['start_x']}, start_y={$this->crop['start_y']}"); $img = $this->CreateImageKeepTransparency($this->crop['width'], $this->crop['height']); imagecopy($img, $this->image, 0, 0, $this->crop['start_x'], $this->crop['start_y'], $this->crop['width'], $this->crop['height']); $this->image = $img; $this->width = $this->crop['width']; $this->height = $this->crop['height']; } if (!$this->upscale) { } if ($this->cropToFit) { $this->log("Resizing using strategy - Crop to fit"); if (!$this->upscale && ($this->width < $this->newWidth || $this->height < $this->newHeight)) { $this->log("Resizing - smaller image, do not upscale."); $posX = 0; $posY = 0; $cropX = 0; $cropY = 0; if ($this->newWidth > $this->width) { $posX = round(($this->newWidth - $this->width) / 2); } if ($this->newWidth < $this->width) { $cropX = round(($this->width/2) - ($this->newWidth/2)); } if ($this->newHeight > $this->height) { $posY = round(($this->newHeight - $this->height) / 2); } if ($this->newHeight < $this->height) { $cropY = round(($this->height/2) - ($this->newHeight/2)); } $this->log(" cwidth: $this->cropWidth"); $this->log(" cheight: $this->cropHeight"); $this->log(" nwidth: $this->newWidth"); $this->log(" nheight: $this->newHeight"); $this->log(" width: $this->width"); $this->log(" height: $this->height"); $this->log(" posX: $posX"); $this->log(" posY: $posY"); $this->log(" cropX: $cropX"); $this->log(" cropY: $cropY"); $imageResized = $this->CreateImageKeepTransparency($this->newWidth, $this->newHeight); imagecopy($imageResized, $this->image, $posX, $posY, $cropX, $cropY, $this->width, $this->height); } else { $cropX = round(($this->cropWidth/2) - ($this->newWidth/2)); $cropY = round(($this->cropHeight/2) - ($this->newHeight/2)); $imgPreCrop = $this->CreateImageKeepTransparency($this->cropWidth, $this->cropHeight); $imageResized = $this->CreateImageKeepTransparency($this->newWidth, $this->newHeight); $this->imageCopyResampled($imgPreCrop, $this->image, 0, 0, 0, 0, $this->cropWidth, $this->cropHeight, $this->width, $this->height); imagecopy($imageResized, $imgPreCrop, 0, 0, $cropX, $cropY, $this->newWidth, $this->newHeight); } $this->image = $imageResized; $this->width = $this->newWidth; $this->height = $this->newHeight; } elseif ($this->fillToFit) { $this->log("Resizing using strategy - Fill to fit"); $posX = 0; $posY = 0; $ratioOrig = $this->width / $this->height; $ratioNew = $this->newWidth / $this->newHeight; if ($ratioOrig < $ratioNew) { $posX = round(($this->newWidth - $this->fillWidth) / 2); } else { $posY = round(($this->newHeight - $this->fillHeight) / 2); } if (!$this->upscale && ($this->width < $this->newWidth && $this->height < $this->newHeight) ) { $this->log("Resizing - smaller image, do not upscale."); $posX = round(($this->newWidth - $this->width) / 2); $posY = round(($this->newHeight - $this->height) / 2); $imageResized = $this->CreateImageKeepTransparency($this->newWidth, $this->newHeight); imagecopy($imageResized, $this->image, $posX, $posY, 0, 0, $this->width, $this->height); } else { $imgPreFill = $this->CreateImageKeepTransparency($this->fillWidth, $this->fillHeight); $imageResized = $this->CreateImageKeepTransparency($this->newWidth, $this->newHeight); $this->imageCopyResampled($imgPreFill, $this->image, 0, 0, 0, 0, $this->fillWidth, $this->fillHeight, $this->width, $this->height); imagecopy($imageResized, $imgPreFill, $posX, $posY, 0, 0, $this->fillWidth, $this->fillHeight); } $this->image = $imageResized; $this->width = $this->newWidth; $this->height = $this->newHeight; } elseif (!($this->newWidth == $this->width && $this->newHeight == $this->height)) { $this->log("Resizing, new height and/or width"); if (!$this->upscale && ($this->width < $this->newWidth || $this->height < $this->newHeight) ) { $this->log("Resizing - smaller image, do not upscale."); if (!$this->keepRatio) { $this->log("Resizing - stretch to fit selected."); $posX = 0; $posY = 0; $cropX = 0; $cropY = 0; if ($this->newWidth > $this->width && $this->newHeight > $this->height) { $posX = round(($this->newWidth - $this->width) / 2); $posY = round(($this->newHeight - $this->height) / 2); } elseif ($this->newWidth > $this->width) { $posX = round(($this->newWidth - $this->width) / 2); $cropY = round(($this->height - $this->newHeight) / 2); } elseif ($this->newHeight > $this->height) { $posY = round(($this->newHeight - $this->height) / 2); $cropX = round(($this->width - $this->newWidth) / 2); } $imageResized = $this->CreateImageKeepTransparency($this->newWidth, $this->newHeight); imagecopy($imageResized, $this->image, $posX, $posY, $cropX, $cropY, $this->width, $this->height); $this->image = $imageResized; $this->width = $this->newWidth; $this->height = $this->newHeight; } } else { $imageResized = $this->CreateImageKeepTransparency($this->newWidth, $this->newHeight); $this->imageCopyResampled($imageResized, $this->image, 0, 0, 0, 0, $this->newWidth, $this->newHeight, $this->width, $this->height); $this->image = $imageResized; $this->width = $this->newWidth; $this->height = $this->newHeight; } } return $this; } public function postResize() { $this->log("### Post-process after resizing"); if ($this->rotateAfter) { $this->log("Rotating image."); $this->rotate($this->rotateAfter, $this->bgColor); } if (isset($this->filters) && is_array($this->filters)) { foreach ($this->filters as $filter) { $this->log("Applying filter {$filter['type']}."); switch ($filter['argc']) { case 0: imagefilter($this->image, $filter['type']); break; case 1: imagefilter($this->image, $filter['type'], $filter['arg1']); break; case 2: imagefilter($this->image, $filter['type'], $filter['arg1'], $filter['arg2']); break; case 3: imagefilter($this->image, $filter['type'], $filter['arg1'], $filter['arg2'], $filter['arg3']); break; case 4: imagefilter($this->image, $filter['type'], $filter['arg1'], $filter['arg2'], $filter['arg3'], $filter['arg4']); break; } } } if ($this->palette) { $this->log("Converting to palette image."); $this->trueColorToPalette(); } if ($this->blur) { $this->log("Blur."); $this->blurImage(); } if ($this->emboss) { $this->log("Emboss."); $this->embossImage(); } if ($this->sharpen) { $this->log("Sharpen."); $this->sharpenImage(); } if ($this->convolve) { $this->imageConvolution(); } return $this; } public function rotate($angle, $bgColor) { $this->log("Rotate image " . $angle . " degrees with filler color."); $color = $this->getBackgroundColor(); $this->image = imagerotate($this->image, $angle, $color); $this->width = imagesx($this->image); $this->height = imagesy($this->image); $this->log("New image dimension width x height: " . $this->width . " x " . $this->height); return $this; } public function rotateExif() { if (!in_array($this->fileType, array(IMAGETYPE_JPEG, IMAGETYPE_TIFF_II, IMAGETYPE_TIFF_MM))) { $this->log("Autorotate ignored, EXIF not supported by this filetype."); return $this; } $exif = exif_read_data($this->pathToImage); if (!empty($exif['Orientation'])) { switch ($exif['Orientation']) { case 3: $this->log("Autorotate 180."); $this->rotate(180, $this->bgColor); break; case 6: $this->log("Autorotate -90."); $this->rotate(-90, $this->bgColor); break; case 8: $this->log("Autorotate 90."); $this->rotate(90, $this->bgColor); break; default: $this->log("Autorotate ignored, unknown value as orientation."); } } else { $this->log("Autorotate ignored, no orientation in EXIF."); } return $this; } public function trueColorToPalette() { $img = imagecreatetruecolor($this->width, $this->height); $bga = imagecolorallocatealpha($img, 0, 0, 0, 127); imagecolortransparent($img, $bga); imagefill($img, 0, 0, $bga); imagecopy($img, $this->image, 0, 0, 0, 0, $this->width, $this->height); imagetruecolortopalette($img, false, 255); imagesavealpha($img, true); if (imageistruecolor($this->image)) { $this->log("Matching colors with true color image."); imagecolormatch($this->image, $img); } $this->image = $img; } public function sharpenImage() { $this->imageConvolution('sharpen'); return $this; } public function embossImage() { $this->imageConvolution('emboss'); return $this; } public function blurImage() { $this->imageConvolution('blur'); return $this; } public function createConvolveArguments($expression) { if (isset($this->convolves[$expression])) { $expression = $this->convolves[$expression]; } $part = explode(',', $expression); $this->log("Creating convolution expressen: $expression"); if (count($part) != 11) { throw new Exception( "Missmatch in argument convolve. Expected comma-separated string with 11 float values. Got $expression." ); } array_walk($part, function ($item, $key) { if (!is_numeric($item)) { throw new Exception("Argument to convolve expression should be float but is not."); } }); return array( array( array($part[0], $part[1], $part[2]), array($part[3], $part[4], $part[5]), array($part[6], $part[7], $part[8]), ), $part[9], $part[10], ); } public function addConvolveExpressions($options) { $this->convolves = array_merge($this->convolves, $options); return $this; } public function imageConvolution($options = null) { $options = $options ? $options : $this->convolve; $this->log("Convolution with '$options'"); $options = explode(":", $options); foreach ($options as $option) { list($matrix, $divisor, $offset) = $this->createConvolveArguments($option); imageconvolution($this->image, $matrix, $divisor, $offset); } return $this; } public function setDefaultBackgroundColor($color) { $this->log("Setting default background color to '$color'."); if (!(strlen($color) == 6 || strlen($color) == 8)) { throw new Exception( "Background color needs a hex value of 6 or 8 digits. 000000-FFFFFF or 00000000-FFFFFF7F.