1
0
mirror of https://github.com/mosbth/cimage.git synced 2025-09-05 05:21:46 +02:00

Compare commits

..

7 Commits
v0.1.1 ... v0.3

Author SHA1 Message Date
Mikael Roos
9e3c7fae82 Prepare tagging v0.3 2012-10-02 23:25:03 +02:00
Mikael Roos
e4c436f52c preparing to tag latest changes 2012-10-02 23:00:39 +02:00
Mikael Roos
5ac715aa48 preparing to tag latest changes 2012-10-02 22:59:14 +02:00
Mikael Roos
0593fec8fb preparing to tag latest changes 2012-10-02 22:58:11 +02:00
Mikael Roos
81f05147aa preparing to tag latest changes 2012-10-02 22:57:05 +02:00
Mikael Roos
12109803cc preparing to tag latest changes 2012-10-02 22:49:43 +02:00
Mikael Roos
e4ff269a60 implemented filters and quality, chenged how arguments was handled. 2012-05-09 17:57:48 +02:00
5 changed files with 426 additions and 108 deletions

View File

@@ -12,14 +12,21 @@ class CImage {
* Properties
*/
private $image = null; // Object for open image
public $pathToImage;
public $imageFolder; // root folder of images
public $imageName; // image filename, may include subdirectory, relative from $imageFolder
public $pathToImage; // $imageFolder . '/' . $imageName;
private $fileExtension;
public $newWidth;
public $newHeight;
private $cropWidth;
private $cropHeight;
public $keepRatio;
public $cropToFit;
public $crop;
public $crop_x;
public $crop_y;
private $quality;
public $filters;
public $saveFolder;
public $newName;
private $newFileName;
@@ -34,21 +41,16 @@ class CImage {
/**
* Constructor, can take arguments to init the object.
*
* @param $pathToImage string the filepath to the image.
* @param $newWidth integer the new width or null.
* @param $newHeight integer the new width or null.
* @param $keepRatio boolean true to keep aspect ratio else false.
* @param $saveFolder string path to folder where to save the new file or null to skip saving.
* @param $newName string new filename or leave to null to autogenerate filename.
* @param string $imageName filename which may contain subdirectory.
* @param string $imageFolder path to root folder for images.
* @param string $saveFolder path to folder where to save the new file or null to skip saving.
* @param string $newName new filename or leave to null to autogenerate filename.
*/
public function __construct($pathToImage=null, $newWidth=null, $newHeight=null,
$keepRatio=true, $crop=false, $saveFolder=null, $newName=null) {
$this->pathToImage = $pathToImage;
public function __construct($imageName=null, $imageFolder=null, $saveFolder=null, $newName=null) {
$this->imageName = ltrim($imageName, '/');
$this->imageFolder = rtrim($imageFolder, '/');
$this->pathToImage = $this->imageFolder . '/' . $this->imageName;
$this->fileExtension = pathinfo($this->pathToImage, PATHINFO_EXTENSION);
$this->newWidth = $newWidth;
$this->newHeight = $newHeight;
$this->keepRatio = $keepRatio;
$this->crop = $crop;
$this->saveFolder = $saveFolder;
$this->newName = $newName;
}
@@ -69,8 +71,25 @@ class CImage {
*/
public function CreateFilename() {
$parts = pathinfo($this->pathToImage);
$crop = $this->crop ? '_c_' : null;
return $this->saveFolder . '/' . $parts['filename'] . '_' . round($this->newWidth) . '_' . round($this->newHeight) . $crop . '.' . $parts['extension'];
$cropToFit = $this->cropToFit ? '_cf' : null;
$crop_x = $this->crop_x ? "_x{$this->crop_x}" : null;
$crop_y = $this->crop_y ? "_y{$this->crop_y}" : null;
$quality = $this->quality == 100 ? null : "_q{$this->quality}";
$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}"];
}
}
}
}
$subdir = str_replace('/', '-', dirname($this->imageName));
$subdir = '.' ? '_.' : $subdir;
return $this->saveFolder . '/' . $subdir . '_' . $parts['filename'] . '_' . round($this->newWidth) . '_' . round($this->newHeight) . $crop . $cropToFit . $crop_x . $crop_y . $quality . $filters . '.' . $parts['extension'];
}
@@ -80,6 +99,9 @@ class CImage {
public function Init() {
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');
is_numeric($this->quality) and $this->quality >= 0 and $this->quality <= 100 or $this->RaiseError('Quality not in range.');
//is_numeric($this->crop_x) && is_numeric($this->crop_y) or $this->RaiseError('Quality not in range.');
//filter
is_readable($this->pathToImage) or $this->RaiseError('File does not exist.');
in_array($this->fileExtension, $this->validExtensions) or $this->RaiseError('Not a valid file extension.');
is_null($this->saveFolder) or is_writable($this->saveFolder) or $this->RaiseError('Save directory does not exist or is not writable.');
@@ -99,7 +121,7 @@ class CImage {
*/
protected function Output($file) {
$time = filemtime($file);
if(isset($_SERVER['If-Modified-Since']) && strtotime($_SERVER['If-Modified-Since']) >= $time){
if(isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) >= $time){
header("HTTP/1.0 304 Not Modified");
} else {
header('Content-type: ' . $this->mime);
@@ -108,7 +130,7 @@ class CImage {
}
exit;
}
/**
* Open image.
@@ -126,110 +148,260 @@ class CImage {
}
/**
* Map filter name to PHP filter and id.
*
* @param string $name the name of the filter.
*/
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 {
$this->RaiseError('No such filter.');
}
}
/**
* Calculate new width and height of image.
*/
protected function CalculateNewWidthAndHeight() {
// Only calculate new width and height if keeping aspect-ratio.
// Crop, use cropped width and height as base for calulations
$width = $this->width;
$height = $this->height;
if($this->crop) {
if(empty($this->crop['width'])) {
$this->crop['width'] = $this->width - $this->crop['start_x'];
}
if(empty($this->crop['height'])) {
$this->crop['height'] = $this->height - $this->crop['start_y'];
}
$width = $this->crop['width'];
$height = $this->crop['height'];
}
// Calculate new width and height if keeping aspect-ratio.
if($this->keepRatio) {
// Both new width and height are set.
if(isset($this->newWidth) && isset($this->newHeight)) {
// Use newWidth and newHeigh as min width/height, image should fit the area.
if($this->crop) {
$ratioWidth = $this->width/$this->newWidth;
$ratioHeight = $this->height/$this->newHeight;
$ratio = ($ratioWidth < $ratioHeight) ? $ratioWidth : $ratioHeight;
$this->cropWidth = $this->width / $ratio;
$this->cropHeight = $this->height / $ratio;
}
// Use newWidth and newHeigh as max width/height, image should not be larger.
else {
$ratioWidth = $this->width/$this->newWidth;
$ratioHeight = $this->height/$this->newHeight;
$ratio = ($ratioWidth > $ratioHeight) ? $ratioWidth : $ratioHeight;
$this->newWidth = $this->width / $ratio;
$this->newHeight = $this->height / $ratio;
}
$ratioWidth = $width / $this->newWidth;
$ratioHeight = $height / $this->newHeight;
$ratio = ($ratioWidth > $ratioHeight) ? $ratioWidth : $ratioHeight;
$this->newWidth = $width / $ratio;
$this->newHeight = $height / $ratio;
}
// Use new width as max-width
elseif(isset($this->newWidth)) {
$factor = (float)$this->newWidth / (float)$this->width;
$this->newHeight = $factor * $this->height;
$factor = (float)$this->newWidth / (float)$width;
$this->newHeight = $factor * $height;
}
// Use new height as max-hight
elseif(isset($this->newHeight)) {
$factor = (float)$this->newHeight / (float)$this->height;
$this->newWidth = $factor * $this->width;
}
$factor = (float)$this->newHeight / (float)$height;
$this->newWidth = $factor * $width;
}
// Use newWidth and newHeigh as min width/height, image should fit the area.
if($this->cropToFit) {
$ratioWidth = $width / $this->newWidth;
$ratioHeight = $height / $this->newHeight;
$ratio = ($ratioWidth < $ratioHeight) ? $ratioWidth : $ratioHeight;
$this->cropWidth = $width / $ratio;
$this->cropHeight = $height / $ratio;
}
}
// Do not keep aspect ratio, but both newWidth and newHeight must be set
else {
$this->newWidth = isset($this->newWidth) ? $this->newWidth : $this->width;
$this->newHeight = isset($this->newHeight) ? $this->newHeight : $this->height;
}
// Crop, ensure to set new width and height
if($this->crop) {
$this->newWidth = isset($this->newWidth) ? $this->newWidth : $this->crop['width'];
$this->newHeight = isset($this->newHeight) ? $this->newHeight : $this->crop['height'];
}
// No new height or width is set, use existing measures.
$this->newWidth = round(isset($this->newWidth) ? $this->newWidth : $this->width);
$this->newHeight = round(isset($this->newHeight) ? $this->newHeight : $this->height);
return $this;
}
/**
* Resize the image and optionally store/cache the new imagefile. Output the image.
*
* @param integer $newWidth the new width or null. Default is null.
* @param integer $newHeight the new width or null. Default is null.
* @param boolean $keepRatio true to keep aspect ratio else false. Default is true.
* @param boolean $cropToFit true to crop image to fit in box specified by $newWidth and $newHeight. Default is false.
* @param integer $quality the quality to use when saving the file, range 0-100, default is full quality which is 100.
* @param array/string $crop converts string of 1,2,3,4 to array 'width'=>1, 'height'=>2, 'start_x'=>3, 'start_y'=>4.
* @param array $filter.
*/
public function ResizeAndOutput() {
public function ResizeAndOutput($args) {
$defaults = array(
'newWidth'=>null,
'newHeight'=>null,
'keepRatio'=>true,
'cropToFit'=>false,
'quality'=>100,
'crop'=>null, //array('width'=>null, 'height'=>null, 'start_x'=>0, 'start_y'=>0),
'filters'=>null,
);
// Convert crop settins from string to array
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],
);
}
// Convert filter settins from array of string to array of array
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 {
$this->RaiseError('Missing arg to filter, review how many arguments are needed at http://php.net/manual/en/function.imagefilter.php');
}
}
$args['filters'][$key] = $filter;
}
}
//echo "<pre>" . print_r($args['filters'], true) . "</pre>";
// Merge default arguments with incoming and set properties.
//$args = array_merge_recursive($defaults, $args);
$args = array_merge($defaults, $args);
foreach($defaults as $key=>$val) {
$this->{$key} = $args[$key];
}
//echo "<pre>" . print_r($this, true) . "</pre>";
// Init the object and do sanity checks on arguments
$this->Init()->CalculateNewWidthAndHeight();
//echo "<pre>" . print_r($this, true) . "</pre>";
// Use original image?
if(is_null($this->newWidth) && is_null($this->newHeight)) {
$this->Output($this->pathToImage);
}
//echo "{$this->newWidth}:{$this->newHeight}";
// Check cache before resizing.
$this->newFileName = $this->CreateFilename();
if(is_readable($this->newFileName)) {
$fileTime = filemtime($this->pathToImage);
$cacheTime = filemtime($this->newFileName);
$fileTime = filemtime($this->pathToImage);
$cacheTime = filemtime($this->newFileName);
if($fileTime <= $cacheTime) {
$this->Output($this->newFileName);
}
}
// Resize and output
// Resize and output and save new to cache
$this->Open()->ResizeAndSave();
}
/**
* Create a image and keep transparency for png and gifs.
*
* $param int $width of the new image.
* @param int $height of the new image.
* @returns image resource.
*/
public function CreateImageKeepTransparency($width, $height) {
//echo $width . "x" . $height . "<br>";
$img = imagecreatetruecolor($width, $height);
/*
if($this->fileExtension == 'png' || ($this->fileExtension == 'gif')) {
imagealphablending($img, false);
imagesavealpha($img, true);
$transparent = imagecolorallocatealpha($img, 255, 255, 255, 127);
imagefilledrectangle($img, 0, 0, $width, $height, $transparent);
}
*/
return $img;
}
/**
* Resize, crop and output the image.
*
* @param $imageQuality number the quality to use when saving the file, default is full quality.
*/
public function ResizeAndSave($imageQuality="100") {
public function ResizeAndSave() {
// Do as crop, take only part of image
if($this->crop) {
//echo "Cropping";
$img = $this->CreateImageKeepTransparency($this->crop['width'], $this->crop['height']);
imagecopyresampled($img, $this->image, 0, 0, $this->crop['start_x'], $this->crop['start_y'], $this->crop['width'], $this->crop['height'], $this->crop['width'], $this->crop['height']);
$this->image = $img;
$this->width = $this->crop['width'];
$this->height = $this->crop['height'];
}
// Resize by crop to fit
if($this->cropToFit) {
//echo "Crop to fit";
$cropX = ($this->cropWidth/2) - ($this->newWidth/2);
$cropY = ($this->cropHeight/2) - ($this->newHeight/2);
$imgPreCrop = imagecreatetruecolor($this->cropWidth, $this->cropHeight);
$imageResized = imagecreatetruecolor($this->newWidth, $this->newHeight);
$imgPreCrop = $this->CreateImageKeepTransparency($this->cropWidth, $this->cropHeight);
$imageResized = $this->CreateImageKeepTransparency($this->newWidth, $this->newHeight);
imagecopyresampled($imgPreCrop, $this->image, 0, 0, 0, 0, $this->cropWidth, $this->cropHeight, $this->width, $this->height);
imagecopyresampled($imageResized, $imgPreCrop, 0, 0, $cropX, $cropY, $this->newWidth, $this->newHeight, $this->newWidth, $this->newHeight);
} else {
$imageResized = imagecreatetruecolor($this->newWidth, $this->newHeight);
}
// as is
else {
$imageResized = $this->CreateImageKeepTransparency($this->newWidth, $this->newHeight);
imagecopyresampled($imageResized, $this->image, 0, 0, 0, 0, $this->newWidth, $this->newHeight, $this->width, $this->height);
}
// Apply filters
if(isset($this->filters) && is_array($this->filters)) {
foreach($this->filters as $filter) {
switch($filter['argc']) {
case 0: imagefilter($imageResized, $filter['type']); break;
case 1: imagefilter($imageResized, $filter['type'], $filter['arg1']); break;
case 2: imagefilter($imageResized, $filter['type'], $filter['arg1'], $filter['arg2']); break;
case 3: imagefilter($imageResized, $filter['type'], $filter['arg1'], $filter['arg2'], $filter['arg3']); break;
case 4: imagefilter($imageResized, $filter['type'], $filter['arg1'], $filter['arg2'], $filter['arg3'], $filter['arg4']); break;
}
}
}
switch($this->fileExtension)
{
case 'jpg':
case 'jpeg':
if(imagetypes() & IMG_JPG) {
if($this->saveFolder) {
imagejpeg($imageResized, $this->newFileName, $imageQuality);
imagejpeg($imageResized, $this->newFileName, $this->quality);
}
$imgFunction = 'imagejpeg';
}
@@ -246,7 +418,7 @@ class CImage {
case 'png':
// Scale quality from 0-100 to 0-9 and invert setting as 0 is best, not 9
$quality = 9 - round(($imageQuality/100) * 9);
$quality = 9 - round(($this->quality/100) * 9);
if (imagetypes() & IMG_PNG) {
if($this->saveFolder) {
imagepng($imageResized, $this->newFileName, $quality);
@@ -259,7 +431,7 @@ class CImage {
break;
}
header('Content-type: ' . $this->mime);
header('Last-Modified: ' . gmdate("D, d M Y H:i:s",time()) . " GMT");
header('Last-Modified: ' . gmdate("D, d M Y H:i:s", time()) . " GMT");
$imgFunction($imageResized);
exit;
}

View File

@@ -1,25 +1,84 @@
Image conversion on the fly using PHP
=====================================
The `CImage.php` contains a class that can resize and crop images and output them to
a webpage. The class has cache of generated images.
About
-------------------------------------
The `CImage.php` is a PHP class that can resize and crop images on the fly and output
them to, for example to a webpage. The class preserves a cache of the generated images
and responds with HTTP 304 (not modified) if the image has not changed.
The file `img.php` uses `CImage.php` to resize images. It is a usecase on how to use
the class.
the class. `img.php` is useful for webpages which want to dynamically resize the images.
The file `test.php` has some testcases that show the results of `img.php` with different
The file `test.php` has testcases that show the results of `img.php` with different
settings.
Start by reviewing the `test.php`, then have a look at `img.php` and finally go through
`CImage.php`.
Enjoy.
CImage lives at github: https://github.com/mosbth/cimage
Mikael Roos (mos@dbwebb.se)
You can try out a live example at: http://dbwebb.se/kod-exempel/cimage/
Enjoy!
Mikael Roos (me@mikaelroos.se)
Installation
-------------------------------------
1. Clone from github: `git://github.com/mosbth/cimage.git`
2. Make the cache directory writable by the webserver.
<pre><code>
chmod 777 cache
</code></pre>
3. Point your browser to `test.php`.
4. Review the settings in `img.php` and try it out.
5. Advanced usage. Put `img.php` in your `/img`-directory. Create a `.htaccess` in your
web root folder containing the following line:
<pre><code>
RewriteEngine on
RewriteRule ^image/(.*)$ img/img.php?src=$1 [QSA,NC,L]
</code></pre>
Now you can access and resize your images through `/image/someimage.jpg?w=80`. Very handy.
Revision history
----------------
-------------------------------------
ToDo.
* Improved support for pre-defined sizes.
* crop-to-fit, add parameter for offset x and y to enable to define which area is the
center of the image from which the crop is done.
* Show how to integrate with WordPress, shortcodes.
* Support for resizing opaque images.
* Clean up code in `CImage.php`.
v0.3 (2012-10-02)
* Added crop. Can crop a area (`width`, `height`, `start_x`, `start_y`) from the original
image.
* Corrected to make the 304 Not Modified header work.
* Pre-defined sizes can be configured for width in `img.php`.
* Corrected to make crop work with width or height in combination with crop-to-fit.
v0.2 (2012-05-09)
* Implemented filters as in http://php.net/manual/en/function.imagefilter.php
* Changed `crop` to `crop_to_fit`, works the same way.
* Changed arguments and sends them in array.
* Added quality-setting.
* Added testcases for above.
v0.1.1 (2012-04-27)
@@ -29,3 +88,6 @@ v0.1.1 (2012-04-27)
v0.1 (2012-04-25)
* Initial release after rewriting some older code I had lying around.
.
..: Copyright 2012 by Mikael Roos (me@mikaelroos.se)

1
cache/README.md vendored Normal file
View File

@@ -0,0 +1 @@
This directory must be writable by the webserver.

71
img.php
View File

@@ -1,34 +1,67 @@
<?php
/**
* Resize images on the fly using cache.
*
*
* @author Mikael Roos mos@dbwebb.se
* @example http://dbwebb.se/kod-exempel/cimage/
* @link https://github.com/mosbth/cimage
*
*/
error_reporting(-1);
set_time_limit(20);
// Append ending slash
$pathToImages = __DIR__.'/img/';
$pathToCache = __DIR__.'/cache/';
$cimageClassFile = __DIR__ .'/CImage.php';
$pathToImages = __DIR__.'/img/';
$pathToCache = __DIR__.'/cache/';
$maxWidth = $maxHeight = 2000;
// Set areas to map constant to value, easier to use with width or height
$area = array(
'w1' => 613,
);
// Get input from querystring
$srcImage = isset($_GET['src']) ? $pathToImages . basename($_GET['src']) : null;
$newWidth = isset($_GET['width']) ? $_GET['width'] : (isset($_GET['w']) ? $_GET['w'] : null);
$newHeight = isset($_GET['height']) ? $_GET['height'] : (isset($_GET['h']) ? $_GET['h'] : null);
$keepRatio = isset($_GET['no-ratio']) ? false : true; // Keep Aspect Ratio?
$crop = isset($_GET['crop']) ? true : false; // Crop image?
$srcImage = isset($_GET['src']) ? $_GET['src'] : null;
$newWidth = isset($_GET['width']) ? $_GET['width'] : (isset($_GET['w']) ? $_GET['w'] : null);
$newHeight = isset($_GET['height']) ? $_GET['height'] : (isset($_GET['h']) ? $_GET['h'] : null);
$keepRatio = isset($_GET['no-ratio']) ? false : true;
$cropToFit = isset($_GET['crop-to-fit']) ? true : false;
$crop = isset($_GET['crop']) ? $_GET['crop'] : (isset($_GET['c']) ? $_GET['c'] : null);
$quality = isset($_GET['quality']) ? $_GET['quality'] : (isset($_GET['q']) ? $_GET['q'] : 100);
// Check to replace area
if(isset($area[$newWidth])) {
$newWidth = $area[$newWidth];
}
// Add all filters to an array
$filters = array();
$filter = isset($_GET['filter']) ? $_GET['filter'] : (isset($_GET['f']) ? $_GET['f'] : null);
if($filter) { $filters[] = $filter; }
for($i=0; $i<10;$i++) {
$filter = isset($_GET["filter{$i}"]) ? $_GET["filter{$i}"] : (isset($_GET["f{$i}"]) ? $_GET["f{$i}"] : null);
if($filter) { $filters[] = $filter; }
}
// Do some sanity checks
!preg_match('/^[\w-\.]+$/', $srcImage) or die('Filename contains invalid characters.');
if(isset($newWidth)) {
$newWidth < 1000 or die('To large width.');
$newWidth > 10 or die('To small width.');
}
if(isset($newHeight)) {
$newHeight < 1000 or die('To large height.');
$newHeight > 10 or die('To small height.');
function errorPage($msg) {
header("Status: 404 Not Found");
die('404: ' . $msg);
}
isset($srcImage) or errorPage('Must set src-attribute.');
preg_match('#^[a-z0-9A-Z-/_\.]+$#', $srcImage) or errorPage('Filename contains invalid characters.');
is_file($pathToImages . '/' . $srcImage) or errorPage('Imagefile does not exists.');
is_writable($pathToCache) or errorPage('Cache-directory does not exists or is not writable.');
is_null($newWidth) or ($newWidth > 10 && $newWidth <= $maxWidth) or errorPage('Width out of range.');
is_null($newHeight) or ($newHeight > 10 && $newHeight <= $maxHeight) or errorPage('Hight out of range.');
$quality >= 0 and $quality <= 100 or errorPage('Quality out of range');
// Create the image object
require(__DIR__.'/CImage.php');
$img = new CImage($srcImage, $newWidth, $newHeight, $keepRatio, $crop, $pathToCache);
$img->ResizeAndOutput();
require($cimageClassFile);
$img = new CImage($srcImage, $pathToImages, $pathToCache);
$img->ResizeAndOutput(array('newWidth'=>$newWidth, 'newHeight'=>$newHeight, 'keepRatio'=>$keepRatio,
'cropToFit'=>$cropToFit, 'quality'=>$quality,
'crop'=>$crop, 'filters'=>$filters,
));

View File

@@ -7,36 +7,86 @@
<h1>Testing <code>CImage.php</code> through <code>img.php</code></h1>
<p>You can test any variation of resizing the images through <a href='img.php?src=wider.jpg&amp;w=200&amp;h=200'>img.php?src=wider.jpg&amp;w=200&amp;h=200</a> or <a href='img.php?src=higher.jpg&amp;w=200&amp;h=200'>img.php?src=higher.jpg&amp;w=200&amp;h=200</a></p>
<p>Supported arguments throught the querystring are:</p>
<ul>
<li>h, height: h=200 sets the height to 200px.
<li>w, width: w=200 sets the width to 200px.
<li>crop: together with both h & w makes the image fit in the box.
<li>h, height: h=200 sets the new height to max 200px.
<li>w, width: w=200 sets the new width to max 200px.
<li>crop-to-fit: set together with both h & w to make the image fit in the box and crop out the rest.
<li>no-ratio: do not keep aspect ratio.
<li>crop: crops an area from the original image, set width, height, start_x and start_y to define the area to crop, for example crop=100,100,10,10.
<li>q, quality: q=70 or quality=70 sets the image quality as value between 0 and 100, default is full quality/100.
<li>f, filter: apply filter to image, f=colorize,0,255,0,0 makes image greener. Supports all filters as defined in <a href='http://php.net/manual/en/function.imagefilter.php'><code>imagefilter()</code></a>
<li>f0-f9: same as f/filter, just add more filters. Applied in order f, f0-f9.
</ul>
<p>Supports <code>.jpg</code>, <code>.png</code> and <code>.gif</code>.</p>
<p>Sourcecode and issues on github: <a href='https://github.com/mosbth/cimage'>https://github.com/mosbth/cimage</a></p>
<p>Mikael Roos (mos@dbwebb.se)</p>
<p>Copyright 2012, Mikael Roos (mos@dbwebb.se)</p>
<h2>Testcases</h2>
<?php
$testcase = array(
array('text'=>'Original image', 'query'=>''),
array('text'=>'Crop out a rectangle of 100x100, start by position 200x200.', 'query'=>'&crop=100,100,200,200'),
array('text'=>'Crop out a full width rectangle with height of 200, start by position 0x100.', 'query'=>'&crop=0,200,0,100'),
array('text'=>'Max width 200.', 'query'=>'&w=200'),
array('text'=>'Max height 200.', 'query'=>'&h=200'),
array('text'=>'Max width 200 and max height 200.', 'query'=>'&w=200&h=200'),
array('text'=>'No-ratio makes image fit in area of width 200 and height 200.', 'query'=>'&w=200&h=200&no-ratio'),
array('text'=>'Crop to fit in width 200 and height 200.', 'query'=>'&w=200&h=200&crop-to-fit'),
array('text'=>'Crop to fit in width 200 and height 100.', 'query'=>'&w=200&h=100&crop-to-fit'),
array('text'=>'Crop to fit in width 100 and height 200.', 'query'=>'&w=100&h=200&crop-to-fit'),
array('text'=>'Quality 70', 'query'=>'&w=200&h=200&quality=70'),
array('text'=>'Quality 40', 'query'=>'&w=200&h=200&quality=40'),
array('text'=>'Quality 10', 'query'=>'&w=200&h=200&quality=10'),
array('text'=>'Filter: Negate', 'query'=>'&w=200&h=200&f=negate'),
array('text'=>'Filter: Grayscale', 'query'=>'&w=200&h=200&f=grayscale'),
array('text'=>'Filter: Brightness 90', 'query'=>'&w=200&h=200&f=brightness,90'),
array('text'=>'Filter: Contrast 50', 'query'=>'&w=200&h=200&f=contrast,50'),
array('text'=>'Filter: Colorize 0,255,0,0', 'query'=>'&w=200&h=200&f=colorize,0,255,0,0'),
array('text'=>'Filter: Edge detect', 'query'=>'&w=200&h=200&f=edgedetect'),
array('text'=>'Filter: Emboss', 'query'=>'&w=200&h=200&f=emboss'),
array('text'=>'Filter: Gaussian blur', 'query'=>'&w=200&h=200&f=gaussian_blur'),
array('text'=>'Filter: Selective blur', 'query'=>'&w=200&h=200&f=selective_blur'),
array('text'=>'Filter: Mean removal', 'query'=>'&w=200&h=200&f=mean_removal'),
array('text'=>'Filter: Smooth 2', 'query'=>'&w=200&h=200&f=smooth,2'),
array('text'=>'Filter: Pixelate 10,10', 'query'=>'&w=200&h=200&f=pixelate,10,10'),
array('text'=>'Multiple filter: Negate, Grayscale and Pixelate 10,10', 'query'=>'&w=200&h=200&&f=negate&f0=grayscale&f1=pixelate,10,10'),
array('text'=>'Crop with width & height and crop-to-fit with quality and filter', 'query'=>'&crop=100,100,100,100&w=200&h=200&crop-to-fit&q=70&f0=grayscale'),
);
?>
<h3>Test case with image <code>wider.jpg</code></h3>
<table>
<caption>Test cases</caption>
<caption>Test case with image <code>wider.jpg</code></caption>
<thead><tr><th>Testcase:</th><th>Result:</th></tr></thead>
<tbody>
<tr><td>Original image of wider.jpg.</td><td><img src='img.php?src=wider.jpg' /></td></tr>
<tr><td>wider.jpg max width 200.</td><td><img src='img.php?src=wider.jpg&amp;w=200' /></td></tr>
<tr><td>wider.jpg max height 200.</td><td><img src='img.php?src=wider.jpg&amp;h=200' /></td></tr>
<tr><td>wider.jpg max width 200 and max height 200.</td><td><img src='img.php?src=wider.jpg&amp;w=200&amp;h=200' /></td></tr>
<tr><td>wider.jpg max width 200 and max height 200 and no-ratio.</td><td><img src='img.php?src=wider.jpg&amp;w=200&amp;h=200&amp;no-ratio' /></td></tr>
<tr><td>wider.jpg max width 200 and max height 200 and cropped.</td><td><img src='img.php?src=wider.jpg&amp;w=200&amp;h=200&amp;crop' /></td></tr>
<tr><td>wider.jpg max width 200 and max height 100 and cropped.</td><td><img src='img.php?src=wider.jpg&amp;w=200&amp;h=100&amp;crop' /></td></tr>
<tr><td>Original image of higher.jpg.</td><td><img src='img.php?src=higher.jpg' /></td></tr>
<tr><td>higher.jpg max width 200.</td><td><img src='img.php?src=higher.jpg&amp;w=200' /></td></tr>
<tr><td>higher.jpg max height 200.</td><td><img src='img.php?src=higher.jpg&amp;h=200' /></td></tr>
<tr><td>higher.jpg max width 200 and max height 200.</td><td><img src='img.php?src=higher.jpg&amp;w=200&amp;h=200' /></td></tr>
<tr><td>higher.jpg max width 200 and max height 200 and no-ratio.</td><td><img src='img.php?src=higher.jpg&amp;w=200&amp;h=200&amp;no-ratio' /></td></tr>
<tr><td>higher.jpg max width 200 and max height 200 and cropped.</td><td><img src='img.php?src=higher.jpg&amp;w=200&amp;h=200&amp;crop' /></td></tr>
<tr><td>higher.jpg max width 200 and max height 100 and cropped.</td><td><img src='img.php?src=higher.jpg&amp;w=200&amp;h=100&amp;crop' /></td></tr>
<?php
foreach($testcase as $key => $val) {
$url = "img.php?src=wider.jpg{$val['query']}";
echo "<tr><td id=w$key><a href=#w$key>$key</a></br>{$val['text']}</br><code><a href='$url'>".htmlentities($url)."</a></code></td><td><img src='$url' /></td></tr>";
}
?>
</tbody>
</table>
<h3>Test case with image <code>higher.jpg</code></h3>
<table>
<caption>Test case with image <code>higher.jpg</code></caption>
<thead><tr><th>Testcase:</th><th>Result:</th></tr></thead>
<tbody>
<?php
foreach($testcase as $key => $val) {
$url = "img.php?src=higher.jpg{$val['query']}";
echo "<tr><td id=h$key><a href=#h$key>$key</a></br>{$val['text']}</br><code><a href='$url'>".htmlentities($url)."</a></code></td><td><img src='$url' /></td></tr>";
}
?>
</tbody>
</table>
</body>
</html>