1
0
mirror of https://github.com/mosbth/cimage.git synced 2025-08-27 17:39:51 +02:00

Compare commits

...

32 Commits

Author SHA1 Message Date
Mikael Roos
1de4830c96 ready for version 0.7.0 2015-02-10 23:56:24 +01:00
Mikael Roos
12796f4263 for release 0.7 2015-02-10 23:10:23 +01:00
Mikael Roos
26a5013593 for release 0.7 2015-02-10 23:09:41 +01:00
Mikael Roos
68176e2d45 for release 0.7 2015-02-10 23:08:00 +01:00
Mikael Roos
c32a594f62 for release 0.7 2015-02-10 23:05:15 +01:00
Mikael Roos
e5ca711c8a for release 0.7 2015-02-10 23:04:29 +01:00
Mikael Roos
2b76fb689c updated versions for single scripts 2015-02-10 22:50:15 +01:00
Mikael Roos
fb9b89a65f updated versions for single scripts 2015-02-10 22:49:17 +01:00
Mikael Roos
c2b037af0d preparing to release v0.7.0-rc-1 2015-02-10 22:45:20 +01:00
Mikael Roos
889dba1ddb Always use password, setting in img_config.php, fix #78. 2015-02-10 22:41:24 +01:00
Mikael Roos
0baea7c346 adding transparent images for test 2015-02-09 08:03:31 +01:00
Mikael Roos
ab4e8a6fae Resize gif keeping transparency #81. 2015-02-09 00:43:38 +01:00
Mikael Roos
641d67d7a0 Resize gif keeping transparency #81. 2015-02-09 00:42:49 +01:00
Mikael Roos
aa009510be Resize gif keeping transparency #81. 2015-02-09 00:40:55 +01:00
Mikael Roos
9348141e65 rename 2015-02-09 00:37:25 +01:00
Mikael Roos
800dcbc248 rename 2015-02-08 19:53:34 +01:00
Mikael Roos
7b18030580 replacing with other testimage 2015-02-08 19:52:51 +01:00
Mikael Roos
e5738c02b1 adding animated gif 2015-02-08 19:52:20 +01:00
Mikael Roos
6478915f3c adding testimage for gif animation 2015-02-08 19:20:10 +01:00
Mikael Roos
ba58ce80c0 adding testimage png transparent 2015-02-08 19:19:42 +01:00
Mikael Roos
d4d645a00e adding transparent gif for test 2015-02-08 19:04:02 +01:00
Mikael Roos
011148b0e8 correcting mode-setting in config 2015-02-02 12:43:55 +01:00
Mikael Roos
eb0fc69036 correcting mode-setting in config 2015-02-02 12:43:01 +01:00
Mikael Roos
c012cb2537 testing before release v0.7.0 2015-02-02 12:39:58 +01:00
Mikael Roos
16a7a3dad5 * Now returns statuscode 500 when something fails #55.
* Three different modes: strict, production, development #44.
* Three files for all-in-one `imgs.php`, `imgp.php`, `imgd.php` #73.
2015-01-29 21:16:32 +01:00
Mikael Roos
bc4e04c3cb change name of all-in-one-file to imgs.php #73 2015-01-28 19:52:10 +01:00
Mikael Roos
3452ea1908 Add all code into one single script #73 2015-01-27 22:40:28 +01:00
Mikael Roos
5e08e5ed80 Enable in config to disallow hotlinking/leeching #46 2015-01-19 00:00:54 +01:00
Mikael Roos
4fae208c4c alias now requires password to work. alias filename is without extension #47. 2015-01-17 19:16:39 +01:00
Mikael Roos
f87dc2967f adding support for alias #47 2015-01-15 23:29:18 +01:00
Mikael Roos
c35587c7e2 create caache directory for remote download if it does not exists #43 2015-01-14 21:00:08 +01:00
Mikael Roos
81e70b7acd Introduced default values for almost all confguration options #72 2015-01-14 20:47:48 +01:00
15 changed files with 12899 additions and 283 deletions

View File

@@ -2,9 +2,9 @@
/**
* Resize and crop images on the fly, store generated images in a cache.
*
* @author Mikael Roos mos@dbwebb.se
* @author Mikael Roos mos@dbwebb.se
* @example http://dbwebb.se/opensource/cimage
* @link https://github.com/mosbth/cimage
* @link https://github.com/mosbth/cimage
*/
class CImage
{
@@ -473,8 +473,16 @@ class CImage
public function downloadRemoteSource($src)
{
$remote = new CRemoteImage();
$cache = $this->saveFolder . "/remote/";
if (!is_dir($cache)) {
if (!is_writable($this->saveFolder)) {
throw new Exception("Can not create remote cache, cachefolder not writable.");
}
mkdir($cache);
$this->log("The remote cache does not exists, creating it.");
}
$cache = $this->saveFolder . "/remote/";
if (!is_writable($cache)) {
$this->log("The remote cache is not writable.");
}
@@ -1305,6 +1313,8 @@ class CImage
$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;
@@ -1989,7 +1999,17 @@ class CImage
imagealphablending($img, false);
imagesavealpha($img, true);
if ($this->bgColorDefault) {
$index = imagecolortransparent($this->image);
if ($index != -1) {
imagealphablending($img, true);
$transparent = imagecolorsforindex($this->image, $index);
$color = imagecolorallocatealpha($img, $transparent['red'], $transparent['green'], $transparent['blue'], $transparent['alpha']);
imagefill($img, 0, 0, $color);
$index = imagecolortransparent($img, $color);
$this->Log("Detected transparent color = " . implode(", ", $transparent) . " at index = $index");
} elseif ($this->bgColorDefault) {
$color = $this->getBackgroundColor($img);
imagefill($img, 0, 0, $color);
@@ -2122,6 +2142,42 @@ class CImage
$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;
}
/**
* Create a hard link, as an alias, to the cached file.
*
* @param string $alias where to store the link,
* filename without extension.
*
* @return $this
*/
public function linkToCacheFile($alias)
{
if ($alias === null) {
$this->log("Ignore creating alias.");
return $this;
}
$alias = $alias . "." . $this->extension;
if (is_readable($alias)) {
unlink($alias);
}
$res = link($this->cacheFileName, $alias);
if ($res) {
$this->log("Created an alias as: $alias");
} else {
$this->log("Failed to create the alias: $alias");
}
return $this;

View File

@@ -1,8 +1,8 @@
<?php
/**
* Get a image from a remote server using HTTP GET and If-Modified-Since.
*
*/
* Get a image from a remote server using HTTP GET and If-Modified-Since.
*
*/
class CRemoteImage
{
/**
@@ -124,6 +124,23 @@ class CRemoteImage
/**
* Check if cache is writable or throw exception.
*
* @return $this
*
* @throws Exception if cahce folder is not writable.
*/
public function isCacheWritable()
{
if (!is_writable($this->saveFolder)) {
throw new Exception("Cache folder is not writable for downloaded files.");
}
return $this;
}
/**
* Decide if the cache should be used or not before trying to download
* a remote file.
@@ -277,8 +294,10 @@ class CRemoteImage
$this->status = $this->http->getStatus();
if ($this->status === 200) {
$this->isCacheWritable();
return $this->save();
} else if ($this->status === 304) {
$this->isCacheWritable();
return $this->updateCacheDetails();
}
@@ -294,7 +313,7 @@ class CRemoteImage
*/
public function loadCacheDetails()
{
$cacheFile = str_replace(["/", ":", "#", ".", "?"], "-", $this->url);
$cacheFile = str_replace(array("/", ":", "#", ".", "?"), "-", $this->url);
$this->fileName = $this->saveFolder . $cacheFile;
$this->fileJson = $this->fileName . ".json";
if (is_readable($this->fileJson)) {

553
README.md
View File

@@ -4,57 +4,52 @@ Image conversion on the fly using PHP
About
-------------------------------------
`CImage` is a PHP class enabling resizing of images through scaling and cropping together with filtering effects -- all using PHP GD. The script `img.php` uses `CImage` to enable server-side image processing together with caching and optimization of the processed images.
<img src="http://dbwebb.se/kod-exempel/cimage/webroot/img.php?src=kodim07.png&w=200&c=140,140,520,340&sharpen"/>
Server-side image processing is a most useful tool for any web developer, `img.php` has an easy to use interface and its powerful when you integrate it with your website. Using it might decrease the time and effort put in managing images and improve your workflow when creating content for websites.
`CImage` is a PHP class enabling resizing of images through scaling, cropping and filtering effects -- using PHP GD. The script `img.php` uses `CImage` to enable server-side image processing utilizing caching and optimization of the processed images.
Server-side image processing is a most useful tool for any web developer, `img.php` has an easy to use interface and its powerful when you integrate it with your website. Using it might decrease the time and effort for managing images and it might improve your workflow for creating content for websites.
This software is free and open source, licensed according MIT.
Use case
Documentation
--------------------------------------
You got an image from your friend who took it with the iPhone and you want to put it up on your website.
<img src="http://dbwebb.se/kod-exempel/cimage/webroot/img.php?src=issue36/me-270.jpg&w=300" alt="">
The original image is looking like this one, scaled down to a width of 300 pixels.
So, you need to rotate it and crop off some parts to make it intresting.
To show it off, I'll autorotate the image based on its EXIF-information, I will crop it to a thumbnail of 100x100 pixels and add a filter to make it greyscale finishing up with a sharpen effect. Just for the show I'll rotate the image 25 degrees - do not ask me why.
Lets call this *the URL-Photoshopper*. This is how the magic looks like.
`img.php?src=issue36/me-270.jpg&w=100&h=100&cf&aro&rb=-25&a=8,30,30,38&f=grayscale`<br>`&convolve=sharpen-alt`
<img src="http://dbwebb.se/kod-exempel/cimage/webroot/img.php?src=issue36/me-270.jpg&w=100&h=100&cf&aro&rb=-25&a=8,30,30,38&f=grayscale&convolve=sharpen-alt" alt="">
For myself, I use `img.php` to put up all images on my website, it gives me the power of affecting the resulting images - without opening up a photo-editing application.
Read full documentation at:
http://dbwebb.se/opensource/cimage
Requirements
--------------------------------------
`CImage` and `img.php` supports GIF (with transparency), JPEG and PNG (8bit transparent, 24bit semi transparent) images. It requires PHP 5.3 and PHP GD. You optionally need the EXIF extension to support auto-rotation of JPEG-images.
`CImage` and `img.php` supports GIF (with transparency), JPEG and PNG (8bit transparent, 24bit semi transparent) images. It requires PHP 5.3 and PHP GD. You optionally need the EXIF extension to support auto-rotation of JPEG-images.
*Version v0.7.x will be the last version to support PHP 5.3. Coming version will require newer version of PHP.*
Installation
--------------------------------------
The [sourcode is available on GitHub](https://github.com/mosbth/cimage). Clone, fork or [download as zip](https://github.com/mosbth/cimage/archive/master.zip).
There are two ways of installing. You either install the whole project which uses the autoloader to include the various files, or you install the all-included bundle that -- for convenience -- contains all code in one script.
###Install source from GitHub
The [sourcode is available on GitHub](https://github.com/mosbth/cimage). Clone, fork or [download as zip](https://github.com/mosbth/cimage/archive/master.zip).
**Latest stable version is v0.7.0 released 2015-02-10.**
I prefer cloning like this. Do switch to the latest stable version.
**Latest stable version is v0.6.1 released 2015-01-08.**
```bash
git clone git://github.com/mosbth/cimage.git
cd cimage
git checkout v0.6.1
git checkout v0.7.0
```
Make the cache-directory writable by the webserver.
@@ -64,60 +59,128 @@ chmod 777 cache
```
###Install all-included bundle
Get going quickly
There are some all-included bundles of `img.php` that can be downloaded and used without dependency to the rest of the sourcecode.
| Scriptname | Description |
|------------|-------------|
| `imgd.php` | Development mode with verbose error reporting and option `&verbose` enabled. |
| `imgp.php` | Production mode logs all errors to file, giving server error 500 for bad usage, option `&verbose` disabled. |
| `imgs.php` | Strict mode logs few errors to file, giving server error 500 for bad usage, option `&verbose` disabled. |
Dowload the version of your choice like this.
```bash
wget https://github.com/mosbth/cimage/tree/v0.7.0/webroot/imgp.php
```
Open up the file in your editor and edit the array `$config`. Ensure that the paths to the image directory and the cache directory matches your environment, or create an own config-file for the script.
Use cases
--------------------------------------
Lets take some use cases to let you know when and how `img.php` might be useful.
### Make a thumbnail
<img src="http://dbwebb.se/kod-exempel/cimage/webroot/img.php?src=kodim04.png&w=80&h=80&cf">
Lets say you have a larger image and you want to make a smaller thumbnail of it with a size of 80x80 pixels. You simply take the image and add constraints on `width`, `height` and you use the resize strategy `crop-to-fit` to crops out the parts of the image that does not fit.
To produce such a thumbnail, create a link like this:
> `img.php?src=kodim04.png&width=80&height=80&crop-to-fit`
### Slightly complexer use case
Perhaps you got an image from a friend. The image was taken with the iPhone and thus rotated.
<img src="http://dbwebb.se/kod-exempel/cimage/webroot/img.php?src=issue36/me-270.jpg&w=250">
The original image is looking like this one, scaled down to a width of 250 pixels.
So, you need to rotate it and crop off some parts to make it intresting.
To show it off, I'll auto-rotate the image based on its EXIF-information, I will crop it to a thumbnail of 100x100 pixels and add a filter to make it greyscale finishing up with a sharpen effect. Just for the show I'll rotate the image 25 degrees - do not ask me why.
Lets call this *the URL-Photoshopper*. This is how the magic looks like.
> `img.php?src=issue36/me-270.jpg&w=100&h=100&cf&aro`
> `&rb=-25&a=8,30,30,38&f=grayscale&convolve=sharpen-alt`
<img src="http://dbwebb.se/kod-exempel/cimage/webroot/img.php?src=issue36/me-270.jpg&w=100&h=100&cf&aro&rb=-25&a=8,30,30,38&f=grayscale&convolve=sharpen-alt">
For myself, I use `img.php` to put up all images on my website, it gives me the power of affecting the resulting images - without opening up a photo-editing application.
Get going quickly
--------------------------------------
###Check out the test page
###Check out the test page
Try it out by pointing your browser to the test file `webroot/test/test.php`. It will show some images and you can review how they are created.
Try it out by pointing your browser to the test file `webroot/test/test.php`. It will show some example images and you can review how they are created.
###Process your first image
###Process your first image
<img src="http://dbwebb.se/kod-exempel/cimage/webroot/img.php?src=kodim04.png&amp;w=w2&amp;a=40,0,50,0" alt=''>
Try it yourself by opening up an image in your browser. Start with `webroot/img.php?src=kodim04.png` and then try to resize it to a thumbnail `webroot/img.php?src=kodim04.png&width=100&height=100&crop-to-fit`.
Try it yourself by opening up an image in your browser. Start with
> `webroot/img.php?src=kodim04.png`
and try to resize it to a thumbnail by adding the options
> `&width=100&height=100&crop-to-fit`
###What does "processing the image" involves?
###What does "processing the image" involves?
Add `&verbose` to the link to get a verbose output of what is happens during image processing. This is useful for developers or those who seek a deeper understanding on how it all works.
Add `&verbose` to the link to get a verbose output of what is happens during image processing. This is useful for developers and those who seek a deeper understanding on how it works behind the scene.
###Check your system
###Check your system
Open up `webroot/check_system.php` if you need to troubleshoot or if you are uncertain if your system has the right extensions loaded.
Open up `webroot/check_system.php` if you are uncertain that your system has the right extensions loaded.
###How does it work?
###How does it work?
Review the settings in `webroot/img_config.php` and check out `webroot/img.php` on how it uses `CImage`.
The programatic flow, just to get you oriented in the environment, is.
1. Start in `img.php`.
2. `img.php` reads configuration details from `img_config.php`.
2. `img.php` reads configuration details from `img_config.php` (if the config-file is available).
3. `img.php` reads and processes incoming `$_GET` arguments to prepare using `CImage`.
4. `img.php` uses `CImage`.
5. `CImage` processes and outputs the image according to how its used.
5. `CImage` processes, caches and outputs the image according to how its used.
Read on to learn more on how to use `img.php`.
Basic usage
Basic usage
--------------------------------------
###Select the source
###Select the source
Open an image through `img.php` by using its `src` attribute.
@@ -125,13 +188,15 @@ Open an image through `img.php` by using its `src` attribute.
It looks like this.
<img src=http://dbwebb.se/kod-exempel/cimage/webroot/img.php?src=kodim13.png&w=w1&save-as=jpg alt="">
<img src="http://dbwebb.se/kod-exempel/cimage/webroot/img.php?src=kodim13.png&w=w1&save-as=jpg">
All images are stored in a directory structure and you access them as `?src=dir1/dir2/image.png`.
All images are stored in a directory structure and you access them as:
> `?src=dir1/dir2/image.png`
###Resize using constraints on width and height
###Resize using constraints on width and height
Create a thumbnail of the image by applying constraints on width and height, or one of them.
@@ -139,13 +204,13 @@ Create a thumbnail of the image by applying constraints on width and height, or
|---------------------|---------------------|---------------------|
| <img src=http://dbwebb.se/kod-exempel/cimage/webroot/img.php?src=kodim13.png&w=150 alt=''> | <img src=http://dbwebb.se/kod-exempel/cimage/webroot/img.php?src=kodim13.png&h=150 alt=''> | <img src=http://dbwebb.se/kod-exempel/cimage/webroot/img.php?src=kodim13.png&w=150&h=150 alt=''> |
By setting width, height or both, the image gets resized to be *not larger* than the defined dimensions *and* keeping its original aspect ratio.
By setting `width`, `height` or both, the image gets resized to be *not larger* than the defined dimensions *and* keeping its original aspect ratio.
Think of the constraints as a imaginary box where the image should fit. With `width=150` and `height=150` the box would have the dimension of 150x150px. A landscape image would fit in that box and its width would be 150px and its height depending on the aspect ratio, but for sure less than 150px. A portrait image would fit with a height of 150px and the width depending on the aspect ratio, but surely less than 150px.
###Resize to fit a certain dimension
###Resize to fit a certain dimension
Creating a thumbnail with a certain dimension of width and height, usually involves stretching or cropping the image to fit in the selected dimensions. Here is how you create a image that has the exact dimensions of 300x150 pixels, by either *stretching*, *cropping* or *fill to fit*.
@@ -159,7 +224,7 @@ Creating a thumbnail with a certain dimension of width and height, usually invol
Learn to crop your images, creative cropping can make wonderful images from appearingly useless originals.
Stretching might work, like in the above example where you can not really notice that the image is stretched. But usually, stretching is not that a good option since it distorts the ratio resulting in a image with incorrect dimensions. Stretching a face may not turn out particularly well.
Stretching might work, like in the above example where you can not really notice that the image is stretched. But usually, stretching is not that a good option since it distorts the ratio. Stretching a face may not turn out particularly well.
Fill to fit is useful when you have some image that must fit in a certain dimension and stretching nor cropping can do it. Carefully choose the background color to make a good resulting image. Choose the same background color as your website and no one will notice.
@@ -169,24 +234,26 @@ Fill to fit is useful when you have some image that must fit in a certain dimens
`img.php` supports a lot of parameters. Combine the parameters to get the desired behavior and resulting image. For example, take the original image, resize it using width, aspect-ratio and crop-to-fit, apply a sharpen effect, save the image as JPEG using quality 30.
| `img.php?src=kodim13.png&w=600&aspect-ratio=4&crop-to-fit&sharpen&save-as=jpg&q=30` |
|-----------------------------------------------------------|
| <img src=http://dbwebb.se/kod-exempel/cimage/webroot/img.php?src=kodim13.png&w=600&aspect-ratio=4&crop-to-fit&sharpen&save-as=jpg&q=30 alt=''> |
> `img.php?src=kodim13.png&w=600&aspect-ratio=4`
> `&crop-to-fit&sharpen&save-as=jpg&q=30`
Here is a list of all parameters that you can use together with `img.php`, grouped by its basic intent of usage.
<img src=http://dbwebb.se/kod-exempel/cimage/webroot/img.php?src=kodim13.png&w=600&aspect-ratio=4&crop-to-fit&sharpen&save-as=jpg&q=30 alt=''>
Here is a list of all parameters that you can use together with `img.php`, grouped by its basic intent of usage.
####Mandatory options and debugging
####Mandatory options and debugging
Option `src` is the only mandatory option. The other in this section is useful for debugging or deciding what version of the target image is used.
Option `src` is the only mandatory option. The options in this section is useful for debugging or deciding what version of the target image is used.
| Parameter | Explained |
| Parameter | Explained |
|----------------|----------------------------------------------|
| `src` | Source image to use, mandatory. `src=img.png` or with subdirectory `src=dir/img.png`. |
| `nc, no-cache` | Do not use the cached version, do all image processing and save a new image to cache. |
| `so, skip-original`| Skip using the original image, always process image, create and use a cached version of the original image. |
| `v, verbose` | Do verbose output and print out a log what happens. Good for debugging, analyzing the process and inspecting how the image is being processed. |
| `json` | Output a JSON-representation of the image, useful for testing or optimizing when one wants to know the image dimensions, before using it. |
| `pwd, password` | Use password to protect unauthorized usage. |
@@ -194,7 +261,7 @@ Option `src` is the only mandatory option. The other in this section is useful f
These options are all affecting the final dimensions, width and height, of the resulting image.
| Parameter | Explained |
| Parameter | Explained |
|----------------|----------------------------------------------|
| `h, height` | `h=200` sets the width to be to max 200px. `h=25%` sets the height to max 25% of its original height. |
| `w, width` | `w=200` sets the height to be max 200px. `w=100%` sets the width to max 100% of its original width. |
@@ -207,7 +274,7 @@ These options are all affecting the final dimensions, width and height, of the r
These options affect strategy to use when resizing an image into a target image that has both width and height set.
| Parameter | Explained |
| Parameter | Explained |
|----------------|----------------------------------------------|
| `nr, no-ratio, stretch` | Do *not* keep aspect ratio when resizing and using both width & height constraints. Results in stretching the image, if needed, to fit in the resulting box. |
| `cf, crop-to-fit` | Set together with both `h` and `w` to make the image fit into dimensions, and crop out the rest of the image. |
@@ -220,10 +287,10 @@ These options affect strategy to use when resizing an image into a target image
These options enable to decide what part of image to crop out.
| Parameter | Explained |
| Parameter | Explained |
|----------------|----------------------------------------------|
| `a, area` | Define the area of the image to work with. Set `area=10,10,10,10` (top,right,bottom,left) to crop out the 10% of the outermost area. It works like an offset to define the part of the image you want to process. Its an alternative of using `crop`. |
| `c, 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` (`crop=width,height,start_x,start_y`). Left top corner is 0, 0. You can use `left`, `right` or `center` when setting start_x. You may use `top`, `bottom` or `center` when setting start_y. |
| `c, 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` (`crop=width,height,start_x,start_y`). Left top corner is 0, 0. You can use `left`, `right` or `center` when setting `start_x`. You may use `top`, `bottom` or `center` when setting `start_y`. |
| `a, area` | Define the area of the image to work with. Set `area=10,10,10,10` (`top`, `right`, `bottom`, `left`) to crop out the 10% of the outermost area. It works like an offset to define the part of the image you want to process. Its an alternative of using `crop`. |
@@ -231,17 +298,17 @@ These options enable to decide what part of image to crop out.
These options are general options affecting processing.
| Parameter | Explained |
| Parameter | Explained |
|----------------|----------------------------------------------|
| `bgc, bg-color` | Set the backgroundcolor to use (if its needed). Use six hex digits as `bgc=00ff00` and 8 digits when using the alpha channel, as this `bgc=00ff007f`. The alpha value can be between 00 and 7f. |
####Processing of image before resizing
####Processing of image before resizing
This option are executed *before* the image is resized.
| Parameter | Explained |
| Parameter | Explained |
|----------------|----------------------------------------------|
| `s, scale` | Scale the image to a size proportional to a percentage of its original size, `scale=25` makes an image 25% of its original size and `size=200` doubles up the image size. Scale is applied before resizing and has no impact of the target width and height. |
| `rb, rotate-before` | Rotate the image before its processed, send the angle as parameter `rb=45`. |
@@ -249,7 +316,7 @@ This option are executed *before* the image is resized.
####Processing of image after resizing
####Processing of image after resizing
These options are executed *after* the image is resized.
@@ -263,169 +330,287 @@ These options are executed *after* the image is resized.
| `convolve` | Use predefined convolution expression as `convolve=sharpen-alt` or a serie of convolutions as `convolve=draw,mean,motion`. These are supported out of the box: `lighten`, `darken`, `sharpen`, `sharpen-alt`, `emboss`, `emboss-alt`, `blur`, `gblur`, `edge`, `edge-alt`, `draw`, `mean`, `motion`. Add your own, or overwrite existing, in `img_config.php`. |
| `f, filter` | Apply filter to image, `f=colorize,0,255,0,0` makes image more green. Supports all filters as defined in [PHP GD `imagefilter()`](http://php.net/manual/en/function.imagefilter.php). |
| `f0, f1-f9` | Same as `filter`, just add more filters. Applied in order `f`, `f0-f9`. |
| `sc, shortcut` | Save longer expressions in `img_config.php`. One place to change your favorite processing options, use as `sc=sepia` which is a shortcut for `&f=grayscale&f0=brightness,-10&f1=contrast,-20&f2=colorize,120,60,0,0&sharpen`. |
| `sc, shortcut` | Save longer expressions in `img_config.php`. One place to change your favorite processing options, use as `sc=sepia` which is a shortcut for `&f=grayscale&f0=brightness,-10&f1=contrast,-20`<br>`&f2=colorize,120,60,0,0&sharpen`. |
Documentation
####Saving image, affecting quality and file size
Options for saving the target image.
| Parameter | Explained |
|----------------|----------------------------------------------|
| `q, quality` | Quality affects lossy compression and file size for JPEG images by setting the quality between 1-100, default is 60. Quality only affects JPEG. |
| `co, compress` | For PNG images it defines the compression algorithm, values can be 0-9, default is defined by PHP GD. Compress only affects PNG. |
| `p, palette` | Create a palette version of the image with up to 256 colors. |
| `sa, save-as` | Save resulting image as JPEG, PNG or GIF, for example `?src=river.png&save-as=gif`. |
| `alias` | Save resulting image as a copy in the alias-directory. |
Carry on reading to view examples on how to use and combine the parameters to achieve desired effects and target images.
The configuration settings in `_config.php`
--------------------------------------
Read full documentation at:
http://dbwebb.se/opensource/cimage
There are several configurations settings that can be used to change the behaviour of `img.php`. Here is an overview, listed as they appear in the default config-file.
| Setting | Explained |
|-------------------------|----------------------------------------------|
| `mode` | Set to "development", "production" or "strict" to match the mode of your environment. It mainly affects the error reporting and if option `verbose` is enabled or not. |
| `autoloader` | Path to the file containing the autoloader. |
| `image_path` | Path to the directory-structure containing the images. |
| `cache_path` | Path to the directory where all the cache-files are stored. |
| `alias_path` | Path to where the alias, or copy, of the images are stored. |
| `password` | Set the password to use. |
| `password_always` | Always require the use of password and match with `password`. |
| `remote_allow` | Allow remote download of images when `src=http://example.com/img.jpg`. |
| `remote_pattern` | Pattern (regexp) to detect if a file is remote or not. |
| `valid_filename` | A regular expression to test if a `src` filename is valid or not. |
| `valid_aliasname` | A regular expression to test if a `alias` filename is valid or not. | |
| `img_path_constraint` | Check that the target image is in a true subdirectory of `img-path` (disables symbolic linking to another part of the filesystem. |
| `default_timezone` | Use to set the timezone if its not already set. |
| `max_width` | Maximal width of the target image. Fails for larger values. |
| `max_height` | Maximal height of the target image. Fails for larger values. |
| `background_color` | Specify a default background color and overwrite the one proposed by `CImage`. |
| `png_filter` | Use (or not) an external command for filter PNG images. |
| `png_filter_cmd` | Path and options to the actual external command. |
| `png_deflate` | Use (or not) an external command for deflating PNG images. |
| `png_deflate_cmd` | Path and options to the actual external command. |
| `jpeg_optimize` | Use (or not) an external command for optimizing JPEG images. |
| `jpeg_optimize_cmd` | Path and options to the actual external command. |
| `convolution_constant` | Constants for own defined convolution expressions. |
| `allow_hotlinking` | Allow or disallow hotlinking7leeching of images. |
| `hotlinking_whitelist` | Array of regular expressions that allow hotlinking (if hotlinking is disabled). |
| `shortcut` | Define own shortcuts for more advanced combination of options to `img.php`. |
| `size_constant` | Create an array with constant values to be used instead of `width` and `height`. |
| `aspect_ratio_constant` | Create an array for constant values to be used with option 'aspect-ratio`. |
Consult the file `webroot/img-config.php` for a complete list together with the default values for each configuration setting. There is an [appendix where you can see the default config-file](#img-config).
Revision history
-------------------------------------
###Create and name the config file
v0.6.2 (2015-01-14)
* Added support for download of remote images #43.
v0.6.1 (2015-01-08)
* Adding compare-page for comparing images. Issue #20.
* Added option `no-upscale, nu` as resizing strategy to decline upscaling of smaller images. Fix #61.
* Minor change in `CImage::resize()`, crop now does imagecopy without resamling.
* Correcting internal details for save-as and response json which indicated wrong colors. Fix #62.
* Fixed fill-to-fit that failed when using aspect-ratio. Fix #52.
* JSON returns correct values for resulting image. Fix #58.
* Corrected behaviour for skip-original. Fix #60.
The file `img.php` looks for the config-file `img_config.php`, and uses it if its found. The three files where everything is included -- `imgd.php`, `imgp.php` and `imgs.php` -- includes an empty `$config`-array which can be overridden by saving a config-file in the same directory. If the script is `imgp.php` then name the config-file `imgp_config.php` and it will find it and use those settings.
v0.6 (2014-12-06)
* Rewrote and added documentation.
* Moved conolution expressesion from `img_config.php` to `CImage`.
* Minor cleaning of properties in `CImage`. Fix #23.
* Adding `webroot/htaccess` to show off how friendly urls can be created for `img.php`. Fix #45.
* Added option `fill-to-fit, ff`. Fix #38.
* Added option `shortcut, sc` to enable configuration of complex expressions. Fix #2.
* Added support for custom convolutions. Fix #49.
* Restructured testprograms. Fix #41.
* Corrected json on PHP 5.3. Fix #42.
* Improving template for tests in `webroot/tests` when testing out #40.
* Adding testcase for #40.
* Adding option `convolve` taking comma-separated list of 11 float-values, wraps and exposes `imageconvoluttion()`. #4
* Adding option `dpr, device-pixel-ratio` which defaults to 1. Set to 2 to get a twice as large image. Useful for Retina displays. Basically a shortcut to enlarge the image.
* Adding utility `cache.bash` to ease gathering stats on cache usage. #21
* Cache-directory can now be readonly and serve all cached files, still failing when need to save files. #5
* Cache now uses same file extension as original image #37.
* Can output image as json format using `json` #11.
Debugging image processing
--------------------------------------
You can visualize what happens during image processing by adding the `v, verbose` parameter. It will then display the resulting image together with a verbose output on what is actually happening behind the scene.
<img src="http://dbwebb.se/image/snapshot/CImage_verbose_output.jpg?w=w2&q=60&sharpen">
This can be most useful for debugging and to understand what actually happen.
The parameter `nc, no-cache` ignores the cached item and will always create a new cached item.
The parameter `so, skip-original` skips the original image, even it that is a best fit. As a result a cached image is created and displayed.
v0.5.3 (2014-11-21)
* Support filenames of uppercase JPEG, JPG, PNG and GIF, as proposed in #37.
* Changing `CImage::output()` as proposed in #37.
* Adding security check that image filename is always below the path `image_path` as specified in `img_config.php` #37.
* Adding configuration item in `img_config.php` for setting valid characters in image filename.
* Moving `webroot/test*` into directory `webroot/test`.
* `webroot/check_system.php` now outputs if extension for exif is loaded.
* Broke API when `initDimensions()` split into two methods, new `initDimensions()` and `loadImageDetails()`.
* Added `autoRotate, aro` to auto rotate image based on EXIF information.
* Added `bgColor, bgc` to use as backgroundcolor when needing a filler color, for example rotate 45.
* Added `rotateBefore, rb` to rotate image a certain angle before processing.
* Added `rotateAfter, ra` to rotate image a certain angle after processing.
* Cleaned up code formatting, removed trailing spaces.
* Removed @ from opening images, better to display correct warning when failing #34, but put it back again.
* Setting gd.jpeg_ignore_warning to true as default #34.
* `webroot/check_system.php` now outputs version of PHP and GD.
* #32 correctly send 404 header when serving an error message.
* Trying to verify issue #29, but can not.
* Adding structure for testprograms together with, use `webroot/test_issue29.php` as sample.
* Improving code formatting.
* Moving parts of verbose output from img.php to CImage.php.
A JSON representation of the image
--------------------------------------
You can ge a JSON representation of the image by adding the option `json`. This can be useful if you need to know the actual dimension of the image.
For example, the following image is created like this:
> `&w=300&save-as=jpg`
<img src="http://dbwebb.se/kod-exempel/cimage/webroot/img.php?src=kodim24.png&w=300&save-as=jpg" alt=''>
Its JSON-representation is retrieved like this:
> `&w=300&save-as=jpg&json`
Which gives the following result.
```php
{
"src":"kodim24.png",
"srcGmdate":"Wed, 12 Feb 2014 13:46:19",
"cache":"_._kodim24_300_200_q60.jpg",
"cacheGmdate":"Sat, 06 Dec 2014 14:09:50",
"filename":"_._kodim24_300_200_q60.jpg",
"width":300,
"height":200,
"aspectRatio":1.5,
"size":11008,
"colors":25751
}
```
I'll use this feature for ease testing of `img.php` and `CImage`. But the feature can also be useful when one really want complete control over the resulting dimension of an image.
v0.5.2 (2014-04-01)
* Correcting issue #26 providing error message when not using postprocessing.
* Correcting issue #27 warning of default timezone.
* Removed default $config options in `img.php`, was not used, all configuration should be in `img_config.php`.
* Verified known bug - sharpen acts as blur in PHP 5.5.9 and 5.5.10 #28
v0.5.1 (2014-02-12)
Implications and considerations
--------------------------------------
* Display image in README-file.
* Create an empty `cache` directory as part of repo.
Here are some thoughts when applying `img.php` on a live system.
v0.5 (2014-02-12)
* Change constant name `CImage::PNG_QUALITY_DEFAULT` to `CImage::PNG_COMPRESSION_DEFAULT`.
* Split JPEG quality and PNG compression, `CImage->quality` and `CImage->compression`
* Changed `img.php` parameter name `d, deflate` to `co, compress`.
* Separating configuration issues from `img.php` to `img_config.php`.
* Format code according to PSR-2.
* Disabled post-processing JPEG and PNG as default.
* This version is supporting PHP 5.3, later versions will require 5.5 or later.
* Using GitHub issue tracking for feature requests and planning.
* Rewrote [the manual](http://dbwebb.se/opensource/cimage).
* Created directory `webroot` and moved some files there.
###Select the proper mode
Select the proper mode for `img.php`. Set it to "strict" or "production" to prevent outsiders to get information about your system. Use only "development" for internal use since its quite verbose in its nature of error reporting.
v0.4.1 (2014-01-27)
* Changed => to == on Modified-Since.
* Always send Last-Modified-Header.
* Added `htmlentities()` to verbose output.
* Fixed support for jpeg, not only jpg.
* Fixed crop whole image by setting crop=0,0,0,0
* Use negative values for crop width & height to base calulation on original width/height and withdraw selected amount.
* Correcting jpeg when setting quality.
* Removed obsolete reference to `$newName` in `CImage::__construct()` (issue 1).
###Put the installation directory outside web root
Edit the config file to put the installation directory -- and the cache directory -- outside of the web root. Best practice would be to store the installation directory and cache, outside of the web root. The only thing needed in the web root is `img.php` and `img_config.php` (if used) which can be placed, for example, in `/img/img.php` or just as `/img.php`.
v0.4 (2013-10-08)
* Improved support for pre-defined sizes.
* Adding grid column size as predefined size, c1-c24 for a 24 column grid. Configure in `img.php`.
* Corrected error on naming cache-files using subdir.
* Corrected calculation error on width & height for crop-to-fit.
* Adding effects for sharpen, emboss and blur through imageconvolution using matrixes.
* crop-to-fit, add parameter for offset x and y to enable to define which area is the, implemented as area.
* Support for resizing opaque images.
* Center of the image from which the crop is done. Improved usage of area to crop.
* Added support for % in width & height.
* Added aspect-ratio.
* Added scale.
* Quality for PNG images is now knows as deflate.
* Added palette to create images with max 256 colors.
* Added usage of all parameters to README.md
* Added documentation here http://dbwebb.se/opensource/cimage
* Adding `.gitignore`
* Re-adding `cache` directory
###Friendly urls through `.htaccess`
Use `.htaccess`and rewrite rules (Apache) to get friendly image urls. Put `img.php` in the `/img` directory. Put the file `.htaccess` in the web root.
**.htaccess for `img.php`.**
```php
#
# Rewrite to have friendly urls to img.php, edit it to suite your environment.
#
# The example is set up as following.
#
# img A directory where all images are stored
# img/me.jpg Access a image as usually.
# img/img.php This is where I choose to place img.php (and img_config.php).
# image/me.jpg Access a image though img.php using htaccess rewrite.
# image/me.jpg?w=300 Using options to img.php.
#
# Subdirectories also work.
# img/me/me.jpg Direct access to the image.
# image/me/me.jpg Accessed through img.php.
# image/me/me.jpg?w=300 Using options to img.php.
#
RewriteRule ^image/(.*)$ img/img.php?src=$1 [QSA,NC,L]
```
You can now access all images through either `/image/car.jpg` (which uses `img.php`) or as usual through `/img/car.jpg` without passing through `img.php`. You send the arguments as usual.
> `/image/car.jpg?w=300&sharpen`
Or a image that resides in a subdirectory.
> `/image/all-cars/car.jpg?w=300&sharpen`
The result is good readable urls to your images. Its easy for the search engine to track and you can use the directory structure already existing in `/img`. Just like one wants to have it.
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.
* Predefined sizes can be configured for width in `img.php`.
* Corrected to make crop work with width or height in combination with crop-to-fit.
###Monitor cache size
There is a utility `cache.bash` included for monitoring the size of the cache-directory. It generates an output like this.
```bash
$ ./cache.bash
Usage: ./cache.bash [cache-dir]
$ ./cache.bash cache
Total size: 27M
Number of files: 225
Top-5 largest files:
1032 cache/_._kodim08_768_512_q60convolvesharpen.png
960 cache/_._kodim08_768_512_q60convolveemboss.png
932 cache/_._kodim08_768_512_q60_rb45.png
932 cache/_._kodim08_768_512_q60_ra45.png
856 cache/_._kodim08_768_512_q60_rb90.png
Last-5 created files:
2014-11-26 16:51 cache/_._kodim08_768_512_q60convolvelighten.png
2014-11-26 16:51 cache/_._kodim08_768_512_q60convolveblur.png
2014-11-26 16:48 cache/_._kodim08_400_267_q60convolvesharpen.png
2014-11-26 16:48 cache/_._kodim08_400_267_q60convolvelighten.png
2014-11-26 16:48 cache/_._kodim08_400_267_q60convolveemboss.png
Last-5 accessed files:
2014-11-27 16:12 _._wider_900_581_q60.jpg
2014-11-27 16:12 _._wider_750_484_q60.jpg
2014-11-27 16:12 _._wider_640_413_q60.jpg
2014-11-27 16:12 _._wider_640_200_c640-200-0-100_q60.jpg
2014-11-27 16:12 _._wider_600_387_q60.jpg
```
Use it as a base if you feel the need to monitor the size och the cache-directory.
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.
###Read-only cache
The cache directory need to be writable for `img.php` to create new files. But its possible to first create all cache-files and then set the directory to be read-only. This will give you a way of shutting of `img.php` from creating new cache files. `img.php` will then continue to work for all images having a cached version but will fail if someone tries to create a new, not previously cached, version of the image.
v0.1.1 (2012-04-27)
* Corrected calculation where both width and height were set.
###Post-processing with external tools
You can use external tools to post-process the images to optimize the file size. This option is available for JPEG and for PNG images. Post-processing is disabled by default, edit `img_config.php` to enable it.
It takes additional time to do post processing, it can take up to a couple of seconds. This is processing to create the cached image, thereafter the cached version will be used and no more post processing needs to be done.
These tools for post processing is not a part of `CImage` and `img.php`, you need to download and install them separately. I use them myself on my system to get an optimal file size.
v0.1 (2012-04-25)
* Initial release after rewriting some older code doing the same, but not that good and flexible.
###Allowing remote download of images
<pre>
You can allow `img.php` to download remote images. That can be enabled in the config-file. However, before doing so, consider the implications on allowing anyone to download a file, hopefully an image, to your server and then the possibility to access it through the webserver.
That sounds scary. It should.
For my own sake I will use it like this, since I consider it a most useful feature.
* Create a special version of `img.php` that has remote download allowed, hide it from public usage.
* Always use a password.
* Download and process the image and save it as an `alias`.
* Integrate the image into your webpage and use the image in the alias directory.
This is an easy way to quickly download a remote image, process and share it.
So, its a scary feature and I might regret I did put it in. Still, its disabled by default and you enable it on your own risk. I have tried to make it as secure as I can, but I might have missed something. I will run it on my own system so I guess I'll find out how secure it is.
Community
--------------------------------------
There is a Swedish forum where you can ask questions, even in English. The forum is a general forum for education in web development, it is not specific for this software.
Ask questions on `CImage` and `img.php` [in the PHP sub forum]([BASEURL]forum/viewforum.php?f=12).
Or ask it on GitHub by creating an issue -- that would be the best place to ask questions.
Or if you fancy irc.
* `irc://irc.bsnet.se/#db-o-webb`
* `irc://irc.freenode.net/#dbwebb`
Trouble- and feature requests
--------------------------------------
Use [GitHub to report issues](https://github.com/mosbth/cimage/issues). Always include the following.
1. Describe very shortly: What are you trying to achieve, what happens, what did you expect.
2. Parameter list used for `img.php`.
3. The image used.
If you request a feature, describe its usage and argument for why you think it fits into `CImage` and `img.php`.
Feel free to fork, clone and create pull requests.
```
.
..: Copyright 2012-2014 by Mikael Roos (me@mikaelroos.se)
</pre>
..: Copyright 2012-2015 by Mikael Roos (me@mikaelroos.se)
```

185
REVISION.md Normal file
View File

@@ -0,0 +1,185 @@
Revision history
=====================================
v0.7.0 (2015-02-10)
-------------------------------------
* Always use password, setting in img_config.php, fix #78.
* Resize gif keeping transparency #81.
* Now returns statuscode 500 when something fails #55.
* Three different modes: strict, production, development #44.
* Three files for all-in-one `imgs.php`, `imgp.php`, `imgd.php` #73.
* Change name of script all-in-one to `webroot/imgs.php` #73.
* Combine all code into one singel script, `webroot/img_single.php` #73.
* Disallow hotlinking/leeching by configuration #46.
* Alias-name is without extension #47.
* Option `alias` now requires `password` to work #47.
* Support for option `password, pwd` to protect usage of `alias` and remote download.
* Added support for option `alias` that creates a link to a cached version of the image #47.
* Create cache directory for remote download if it does not exists.
* Cleaned up `img_config.php` and introduced default values for almost all options #72.
v0.6.2 (2015-01-14)
-------------------------------------
* Added support for download of remote images #43.
* Added autoloader.
v0.6.1 (2015-01-08)
-------------------------------------
* Adding compare-page for comparing images. Issue #20.
* Added option `no-upscale, nu` as resizing strategy to decline upscaling of smaller images. Fix #61.
* Minor change in `CImage::resize()`, crop now does imagecopy without resamling.
* Correcting internal details for save-as and response json which indicated wrong colors. Fix #62.
* Fixed fill-to-fit that failed when using aspect-ratio. Fix #52.
* JSON returns correct values for resulting image. Fix #58.
* Corrected behaviour for skip-original. Fix #60.
v0.6 (2014-12-06)
-------------------------------------
* Rewrote and added documentation.
* Moved conolution expressesion from `img_config.php` to `CImage`.
* Minor cleaning of properties in `CImage`. Fix #23.
* Adding `webroot/htaccess` to show off how friendly urls can be created for `img.php`. Fix #45.
* Added option `fill-to-fit, ff`. Fix #38.
* Added option `shortcut, sc` to enable configuration of complex expressions. Fix #2.
* Added support for custom convolutions. Fix #49.
* Restructured testprograms. Fix #41.
* Corrected json on PHP 5.3. Fix #42.
* Improving template for tests in `webroot/tests` when testing out #40.
* Adding testcase for #40.
* Adding option `convolve` taking comma-separated list of 11 float-values, wraps and exposes `imageconvoluttion()`. #4
* Adding option `dpr, device-pixel-ratio` which defaults to 1. Set to 2 to get a twice as large image. Useful for Retina displays. Basically a shortcut to enlarge the image.
* Adding utility `cache.bash` to ease gathering stats on cache usage. #21
* Cache-directory can now be readonly and serve all cached files, still failing when need to save files. #5
* Cache now uses same file extension as original image #37.
* Can output image as json format using `json` #11.
v0.5.3 (2014-11-21)
-------------------------------------
* Support filenames of uppercase JPEG, JPG, PNG and GIF, as proposed in #37.
* Changing `CImage::output()` as proposed in #37.
* Adding security check that image filename is always below the path `image_path` as specified in `img_config.php` #37.
* Adding configuration item in `img_config.php` for setting valid characters in image filename.
* Moving `webroot/test*` into directory `webroot/test`.
* `webroot/check_system.php` now outputs if extension for exif is loaded.
* Broke API when `initDimensions()` split into two methods, new `initDimensions()` and `loadImageDetails()`.
* Added `autoRotate, aro` to auto rotate image based on EXIF information.
* Added `bgColor, bgc` to use as backgroundcolor when needing a filler color, for example rotate 45.
* Added `rotateBefore, rb` to rotate image a certain angle before processing.
* Added `rotateAfter, ra` to rotate image a certain angle after processing.
* Cleaned up code formatting, removed trailing spaces.
* Removed @ from opening images, better to display correct warning when failing #34, but put it back again.
* Setting gd.jpeg_ignore_warning to true as default #34.
* `webroot/check_system.php` now outputs version of PHP and GD.
* #32 correctly send 404 header when serving an error message.
* Trying to verify issue #29, but can not.
* Adding structure for testprograms together with, use `webroot/test_issue29.php` as sample.
* Improving code formatting.
* Moving parts of verbose output from img.php to CImage.php.
v0.5.2 (2014-04-01)
-------------------------------------
* Correcting issue #26 providing error message when not using postprocessing.
* Correcting issue #27 warning of default timezone.
* Removed default $config options in `img.php`, was not used, all configuration should be in `img_config.php`.
* Verified known bug - sharpen acts as blur in PHP 5.5.9 and 5.5.10 #28
v0.5.1 (2014-02-12)
-------------------------------------
* Display image in README-file.
* Create an empty `cache` directory as part of repo.
v0.5 (2014-02-12)
-------------------------------------
* Change constant name `CImage::PNG_QUALITY_DEFAULT` to `CImage::PNG_COMPRESSION_DEFAULT`.
* Split JPEG quality and PNG compression, `CImage->quality` and `CImage->compression`
* Changed `img.php` parameter name `d, deflate` to `co, compress`.
* Separating configuration issues from `img.php` to `img_config.php`.
* Format code according to PSR-2.
* Disabled post-processing JPEG and PNG as default.
* This version is supporting PHP 5.3, later versions will require 5.5 or later.
* Using GitHub issue tracking for feature requests and planning.
* Rewrote [the manual](http://dbwebb.se/opensource/cimage).
* Created directory `webroot` and moved some files there.
v0.4.1 (2014-01-27)
-------------------------------------
* Changed => to == on Modified-Since.
* Always send Last-Modified-Header.
* Added `htmlentities()` to verbose output.
* Fixed support for jpeg, not only jpg.
* Fixed crop whole image by setting crop=0,0,0,0
* Use negative values for crop width & height to base calulation on original width/height and withdraw selected amount.
* Correcting jpeg when setting quality.
* Removed obsolete reference to `$newName` in `CImage::__construct()` (issue 1).
v0.4 (2013-10-08)
-------------------------------------
* Improved support for pre-defined sizes.
* Adding grid column size as predefined size, c1-c24 for a 24 column grid. Configure in `img.php`.
* Corrected error on naming cache-files using subdir.
* Corrected calculation error on width & height for crop-to-fit.
* Adding effects for sharpen, emboss and blur through imageconvolution using matrixes.
* crop-to-fit, add parameter for offset x and y to enable to define which area is the, implemented as area.
* Support for resizing opaque images.
* Center of the image from which the crop is done. Improved usage of area to crop.
* Added support for % in width & height.
* Added aspect-ratio.
* Added scale.
* Quality for PNG images is now knows as deflate.
* Added palette to create images with max 256 colors.
* Added usage of all parameters to README.md
* Added documentation here http://dbwebb.se/opensource/cimage
* Adding `.gitignore`
* Re-adding `cache` directory
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.
* Predefined 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)
-------------------------------------
* Corrected calculation where both width and height were set.
v0.1 (2012-04-25)
-------------------------------------
* Initial release after rewriting some older code doing the same, but not that good and flexible.

74
create-img-single.bash Executable file
View File

@@ -0,0 +1,74 @@
#!/bin/bash
#
# Paths and settings
#
TARGET_D="webroot/imgd.php"
TARGET_P="webroot/imgp.php"
TARGET_S="webroot/imgs.php"
NEWLINES="\n\n\n"
#
# Specify the utilities used
#
ECHO="printf"
#
# Main, start by checking basic usage
#
if [ $# -gt 0 ]
then
$ECHO "Usage: $0\n"
exit 1
fi
#
# Print out details on cache-directory
#
$ECHO "Creating '$TARGET_D', '$TARGET_P' and '$TARGET_S' by combining the following files:"
$ECHO "\n"
$ECHO "\n webroot/img_header.php"
$ECHO "\n CHttpGet.php"
$ECHO "\n CRemoteImage.php"
$ECHO "\n CImage.php"
$ECHO "\n webroot/img.php"
$ECHO "\n"
$ECHO "\n'$TARGET_D' is for development mode."
$ECHO "\n'$TARGET_P' is for production mode (default mode)."
$ECHO "\n'$TARGET_S' is for strict mode."
$ECHO "\n"
$ECHO "\nPress enter to continue. "
read answer
#
# Create the $TARGET_? files
#
cat webroot/img_header.php > $TARGET_P
cat webroot/img_header.php | sed "s|//'mode' => 'production',|'mode' => 'development',|" > $TARGET_D
cat webroot/img_header.php | sed "s|//'mode' => 'production',|'mode' => 'development',|" > $TARGET_S
$ECHO "$NEWLINES" | tee -a $TARGET_D $TARGET_P $TARGET_S > /dev/null
tail -n +2 CHttpGet.php | tee -a $TARGET_D $TARGET_P $TARGET_S > /dev/null
$ECHO "$NEWLINES" | tee -a $TARGET_D $TARGET_P $TARGET_S > /dev/null
tail -n +2 CRemoteImage.php | tee -a $TARGET_D $TARGET_P $TARGET_S > /dev/null
$ECHO "$NEWLINES" | tee -a $TARGET_D $TARGET_P $TARGET_S > /dev/null
tail -n +2 CImage.php | tee -a $TARGET_D $TARGET_P $TARGET_S > /dev/null
$ECHO "$NEWLINES" | tee -a $TARGET_D $TARGET_P $TARGET_S > /dev/null
tail -n +2 webroot/img.php | tee -a $TARGET_D $TARGET_P $TARGET_S > /dev/null
$ECHO "$NEWLINES" | tee -a $TARGET_D $TARGET_P $TARGET_S > /dev/null
$ECHO "\nDone."
$ECHO "\n"
$ECHO "\n"

View File

@@ -1,9 +1,15 @@
<?php
/**
* Resize images on the fly using CImage, configuration is made in file named.
* Resize and crop images on the fly, store generated images in a cache.
*
* @author Mikael Roos mos@dbwebb.se
* @example http://dbwebb.se/opensource/cimage
* @link https://github.com/mosbth/cimage
*
*/
$version = "v0.7.0 (2015-02-10)";
/**
@@ -15,8 +21,16 @@
*/
function errorPage($msg)
{
header("HTTP/1.0 404 Not Found");
die('img.php say 404: ' . $msg);
global $mode;
header("HTTP/1.0 500 Internal Server Error");
if ($mode == 'development') {
die("[img.php] $msg");
} else {
error_log("[img.php] $msg");
die("HTTP/1.0 500 Internal Server Error");
}
}
@@ -114,20 +128,78 @@ function verbose($msg = null)
/**
* Get configuration options from file.
* Get configuration options from file, if the file exists, else use $config
* if its defined or create an empty $config.
*/
$configFile = __DIR__.'/'.basename(__FILE__, '.php').'_config.php';
$config = require $configFile;
call_user_func($config['error_reporting']);
if (is_file($configFile)) {
$config = require $configFile;
} else if (!isset($config)) {
$config = array();
}
/**
* verbose, v - do a verbose dump of what happens
*/
$verbose = getDefined(array('verbose', 'v'), true, false);
verbose("img.php version = $version");
/**
* Set mode as strict, production or development.
* Default is production environment.
*/
$mode = getConfig('mode', 'production');
// Settings for any mode
set_time_limit(20);
ini_set('gd.jpeg_ignore_warning', 1);
if (!extension_loaded('gd')) {
errorPage("Extension gd is nod loaded.");
}
// Specific settings for each mode
if ($mode == 'strict') {
error_reporting(0);
ini_set('display_errors', 0);
ini_set('log_errors', 1);
$verbose = false;
} else if ($mode == 'production') {
error_reporting(-1);
ini_set('display_errors', 0);
ini_set('log_errors', 1);
$verbose = false;
} else if ($mode == 'development') {
error_reporting(-1);
ini_set('display_errors', 1);
ini_set('log_errors', 0);
} else {
errorPage("Unknown mode: $mode");
}
verbose("mode = $mode");
verbose("error log = " . ini_get('error_log'));
/**
* Set default timezone if not set or if its set in the config-file.
*/
if (isset($config['default_timezone'])) {
date_default_timezone_set($config['default_timezone']);
$defaultTimezone = getConfig('default_timezone', null);
if ($defaultTimezone) {
date_default_timezone_set($defaultTimezone);
} else if (!ini_get('default_timezone')) {
date_default_timezone_set('UTC');
}
@@ -135,9 +207,73 @@ if (isset($config['default_timezone'])) {
/**
* verbose, v - do a verbose dump of what happens
* Check if passwords are configured, used and match.
* Options decide themself if they require passwords to be used.
*/
$verbose = getDefined(array('verbose', 'v'), true, false);
$pwdConfig = getConfig('password', false);
$pwdAlways = getConfig('password_always', false);
$pwd = get(array('password', 'pwd'), null);
// Check if passwords match, if configured to use passwords
$passwordMatch = null;
if ($pwdAlways) {
$passwordMatch = ($pwdConfig === $pwd);
if (!$passwordMatch) {
errorPage("Password required and does not match or exists.");
}
} elseif ($pwdConfig && $pwd) {
$passwordMatch = ($pwdConfig === $pwd);
}
verbose("password match = $passwordMatch");
/**
* Prevent hotlinking, leeching, of images by controlling who access them
* from where.
*
*/
$allowHotlinking = getConfig('allow_hotlinking', true);
$hotlinkingWhitelist = getConfig('hotlinking_whitelist', array());
$serverName = isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : null;
$referer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : null;
$refererHost = parse_url($referer, PHP_URL_HOST);
if (!$allowHotlinking) {
if ($passwordMatch) {
; // Always allow when password match
} else if ($passwordMatch === false) {
errorPage("Hotlinking/leeching not allowed when password missmatch.");
} else if (!$referer) {
errorPage("Hotlinking/leeching not allowed and referer is missing.");
} else if (strcmp($serverName, $refererHost) == 0) {
; // Allow when serverName matches refererHost
} else if (!empty($hotlinkingWhitelist)) {
$allowedByWhitelist = false;
foreach ($hotlinkingWhitelist as $val) {
if (preg_match($val, $refererHost)) {
$allowedByWhitelist = true;
}
}
if (!$allowedByWhitelist) {
errorPage("Hotlinking/leeching not allowed by whitelist.");
}
} else {
errorPage("Hotlinking/leeching not allowed.");
}
}
verbose("allow_hotlinking = $allowHotlinking");
verbose("referer = $referer");
verbose("referer host = $refererHost");
@@ -165,22 +301,10 @@ $img->setVerbose($verbose);
/**
* Allow or disallow remote download of images from other servers.
* Passwords apply if used.
*
*/
$allowRemote = getConfig('remote_allow', false);
$remotePwd = getConfig('remote_password', false);
$pwd = get(array('password', 'pwd'), null);
// Check if passwords match, if configured to use passwords
$passwordMatch = null;
if ($remotePwd != false) {
if ($remotePwd == $pwd) {
$passwordMatch = true;
} else {
$passwordMatch = false;
errorPage('Trying to download remote image but missing password.');
}
}
if ($allowRemote && $passwordMatch !== false) {
$pattern = getConfig('remote_pattern', null);
@@ -193,16 +317,18 @@ if ($allowRemote && $passwordMatch !== false) {
* shortcut, sc - extend arguments with a constant value, defined
* in config-file.
*/
$shortcut = get(array('shortcut', 'sc'), null);
$shortcut = get(array('shortcut', 'sc'), null);
$shortcutConfig = getConfig('shortcut', array(
'sepia' => "&f=grayscale&f0=brightness,-10&f1=contrast,-20&f2=colorize,120,60,0,0&sharpen",
));
verbose("shortcut = $shortcut");
if (isset($shortcut)
&& isset($config['shortcut'])
&& isset($config['shortcut'][$shortcut])) {
&& isset($shortcutConfig[$shortcut])) {
parse_str($config['shortcut'][$shortcut], $get);
verbose("shortcut-constant = {$config['shortcut'][$shortcut]}");
parse_str($shortcutConfig[$shortcut], $get);
verbose("shortcut-constant = {$shortcutConfig[$shortcut]}");
$_GET = array_merge($_GET, $get);
}
@@ -214,21 +340,23 @@ if (isset($shortcut)
$srcImage = get('src')
or errorPage('Must set src-attribute.');
// Check for valid/invalid characters
preg_match($config['valid_filename'], $srcImage)
or errorPage('Filename contains invalid characters.');
$imagePath = getConfig('image_path', __DIR__ . '/img/');
$imagePathConstraint = getConfig('image_path_constraint', true);
$validFilename = getConfig('valid_filename', '#^[a-z0-9A-Z-/_\.:]+$#');
preg_match($validFilename, $srcImage)
or errorPage('Filename contains invalid characters.');
if ($allowRemote && $img->isRemoteSource($srcImage)) {
// If source is a remote file, ignore local file checks.
} else if ($config['image_path_constraint']) {
} else if ($imagePathConstraint) {
// Check that the image is a file below the directory 'image_path'.
$pathToImage = realpath($config['image_path'] . $srcImage);
$imageDir = realpath($config['image_path']);
$pathToImage = realpath($imagePath . $srcImage);
$imageDir = realpath($imagePath);
is_file($pathToImage)
or errorPage(
@@ -243,18 +371,45 @@ if ($allowRemote && $img->isRemoteSource($srcImage)) {
);
}
verbose("src = $srcImage");
/**
* Manage size constants from config file, use constants to replace values
* for width and height.
*/
$sizeConstant = getConfig('size_constant', function () {
// Set sizes to map constant to value, easier to use with width or height
$sizes = array(
'w1' => 613,
'w2' => 630,
);
// Add grid column width, useful for use as predefined size for width (or height).
$gridColumnWidth = 30;
$gridGutterWidth = 10;
$gridColumns = 24;
for ($i = 1; $i <= $gridColumns; $i++) {
$sizes['c' . $i] = ($gridColumnWidth + $gridGutterWidth) * $i - $gridGutterWidth;
}
return $sizes;
});
$sizes = call_user_func($sizeConstant);
/**
* width, w - set target width, affecting the resulting image width, height and resize options
*/
$newWidth = get(array('width', 'w'));
$newWidth = get(array('width', 'w'));
$maxWidth = getConfig('max_width', 2000);
// Check to replace predefined size
$sizes = call_user_func($config['size_constant']);
if (isset($sizes[$newWidth])) {
$newWidth = $sizes[$newWidth];
}
@@ -265,7 +420,7 @@ if ($newWidth[strlen($newWidth)-1] == '%') {
or errorPage('Width % not numeric.');
} else {
is_null($newWidth)
or ($newWidth > 10 && $newWidth <= $config['max_width'])
or ($newWidth > 10 && $newWidth <= $maxWidth)
or errorPage('Width out of range.');
}
@@ -277,6 +432,7 @@ verbose("new width = $newWidth");
* height, h - set target height, affecting the resulting image width, height and resize options
*/
$newHeight = get(array('height', 'h'));
$maxHeight = getConfig('max_height', 2000);
// Check to replace predefined size
if (isset($sizes[$newHeight])) {
@@ -289,7 +445,7 @@ if ($newHeight[strlen($newHeight)-1] == '%') {
or errorPage('Height % out of range.');
} else {
is_null($newHeight)
or ($newHeight > 10 && $newHeight <= $config['max_height'])
or ($newHeight > 10 && $newHeight <= $maxHeight)
or errorPage('Hight out of range.');
}
@@ -300,10 +456,21 @@ verbose("new height = $newHeight");
/**
* aspect-ratio, ar - affecting the resulting image width, height and resize options
*/
$aspectRatio = get(array('aspect-ratio', 'ar'));
$aspectRatio = get(array('aspect-ratio', 'ar'));
$aspectRatioConstant = getConfig('aspect_ratio_constant', function () {
return array(
'3:1' => 3/1,
'3:2' => 3/2,
'4:3' => 4/3,
'8:5' => 8/5,
'16:10' => 16/10,
'16:9' => 16/9,
'golden' => 1.618,
);
});
// Check to replace predefined aspect ratio
$aspectRatios = call_user_func($config['aspect_ratio_constant']);
$aspectRatios = call_user_func($aspectRatioConstant);
$negateAspectRatio = ($aspectRatio[0] == '!') ? true : false;
$aspectRatio = $negateAspectRatio ? substr($aspectRatio, 1) : $aspectRatio;
@@ -335,9 +502,11 @@ verbose("crop to fit = $cropToFit");
/**
* Set default background color from config file.
*/
if (isset($config['background_color'])) {
$img->setDefaultBackgroundColor($config['background_color']);
verbose("Using default background_color = {$config['background_color']}");
$backgroundColor = getConfig('background_color', null);
if ($backgroundColor) {
$img->setDefaultBackgroundColor($backgroundColor);
verbose("Using default background_color = $backgroundColor");
}
@@ -578,11 +747,12 @@ verbose("dpr = $dpr");
* convolve - image convolution as in http://php.net/manual/en/function.imageconvolution.php
*/
$convolve = get('convolve', null);
$convolutionConstant = getConfig('convolution_constant', array());
// Check if the convolve is matching an existing constant
if ($convolve && isset($config['convolution_constant'])) {
$img->addConvolveExpressions($config['convolution_constant']);
verbose("convolve constant = " . print_r($config['convolution_constant'], 1));
if ($convolve && isset($convolutionConstant)) {
$img->addConvolveExpressions($convolutionConstant);
verbose("convolve constant = " . print_r($convolutionConstant, 1));
}
verbose("convolve = " . print_r($convolve, 1));
@@ -598,6 +768,50 @@ verbose("upscale = $upscale");
/**
* Get details for post processing
*/
$postProcessing = getConfig('postprocessing', array(
'png_filter' => false,
'png_filter_cmd' => '/usr/local/bin/optipng -q',
'png_deflate' => false,
'png_deflate_cmd' => '/usr/local/bin/pngout -q',
'jpeg_optimize' => false,
'jpeg_optimize_cmd' => '/usr/local/bin/jpegtran -copy none -optimize',
));
/**
* alias - Save resulting image to another alias name.
* Password always apply, must be defined.
*/
$alias = get('alias', null);
$aliasPath = getConfig('alias_path', null);
$validAliasname = getConfig('valid_aliasname', '#^[a-z0-9A-Z-_]+$#');
$aliasTarget = null;
if ($alias && $aliasPath && $passwordMatch) {
$aliasTarget = $aliasPath . $alias;
$useCache = false;
is_writable($aliasPath)
or errorPage("Directory for alias is not writable.");
preg_match($validAliasname, $alias)
or errorPage('Filename for alias contains invalid characters. Do not add extension.');
} else if ($alias) {
errorPage('Alias is not enabled in the config file or password not matching.');
}
verbose("alias = $alias");
/**
* Display image if verbose mode
*/
@@ -630,13 +844,20 @@ EOD;
/**
* Get the cachepath from config.
*/
$cachePath = getConfig('cache_path', __DIR__ . '/../cache/');
/**
* Load, process and output the image
*/
$img->log("Incoming arguments: " . print_r(verbose(), 1))
->setSaveFolder($config['cache_path'])
->setSaveFolder($cachePath)
->useCache($useCache)
->setSource($srcImage, $config['image_path'])
->setSource($srcImage, $imagePath)
->setOptions(
array(
// Options for calculate dimensions
@@ -679,12 +900,13 @@ $img->log("Incoming arguments: " . print_r(verbose(), 1))
->setJpegQuality($quality)
->setPngCompression($compress)
->useOriginalIfPossible($useOriginal)
->generateFilename($config['cache_path'])
->generateFilename($cachePath)
->useCacheIfPossible($useCache)
->load()
->preResize()
->resize()
->postResize()
->setPostProcessingOptions($config['postprocessing'])
->setPostProcessingOptions($postProcessing)
->save()
->linkToCacheFile($aliasTarget)
->output();

BIN
webroot/img/apple_trans.gif Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

BIN
webroot/img/glider_anim.gif Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

View File

@@ -7,8 +7,23 @@
*/
return array(
/**
* Set mode as 'strict', 'production' or 'development'.
*
* Default values:
* mode: 'production'
*/
'mode' => 'development',
//'mode' => 'production', // 'development', 'strict'
/**
* Where are the sources for the classfiles.
*
* Default values:
* autoloader: null // used from v0.6.2
* cimage_class: null // used until v0.6.1
*/
'autoloader' => __DIR__ . '/../autoload.php',
//'cimage_class' => __DIR__ . '/../CImage.php',
@@ -17,50 +32,78 @@ return array(
/**
* Paths, where are the images stored and where is the cache.
* End all paths with a slash.
*
* Default values:
* image_path: __DIR__ . '/img/'
* cache_path: __DIR__ . '/../cache/'
* alias_path: null
*/
'image_path' => __DIR__ . '/img/',
'cache_path' => __DIR__ . '/../cache/',
//'alias_path' => __DIR__ . '/img/alias/',
/**
* Check that the imagefile is a file below 'image_path' using realpath().
* Security constraint to avoid reaching images outside image_path.
* This means that symbolic links to images outside the image_path will fail.
*/
'image_path_constraint' => true,
/**
* A regexp for validating characters in the image filename.
*/
'valid_filename' => '#^[a-z0-9A-Z-/_\.:]+$#',
* Use password to protect from missusage, send &pwd=... or &password=..
* with the request to match the password or set to false to disable.
* Passwords are only used together with the options for remote download
* and aliasing.
*
* Default values.
* password: false // as in do not use password
* password_always: false // do not always require password,
*/
//'password' => false, // "secret-password",
//'password_always' => false, // always require password,
/**
* Allow or disallow downloading of remote files, images available on
* some remote server. Default is to disallow.
* Use password to protect from missusage, send &pwd=... or &password=..
* with the request to match the password or set to false to disable.
*
* Default values.
* remote_allow: false
* remote_password: false // as in do not use password
* remote_pattern: null // use default values from CImage
*/
//'remote_allow' => true,
//'remote_password' => false, // "secret-password",
//'remote_pattern' => '#^https?://#',
/**
* Set default timezone, it defaults to UTC if not specified.
* A regexp for validating characters in the image or alias filename.
*
* Default value:
* valid_filename: '#^[a-z0-9A-Z-/_\.:]+$#'
* valid_aliasname: '#^[a-z0-9A-Z-_]+$#'
*/
//'default_timezone' => 'UTC',
//'valid_filename' => '#^[a-z0-9A-Z-/_\.:]+$#',
//'valid_aliasname' => '#^[a-z0-9A-Z-_]+$#',
/**
* Check that the imagefile is a file below 'image_path' using realpath().
* Security constraint to avoid reaching images outside image_path.
* This means that symbolic links to images outside the image_path will fail.
*
* Default value:
* image_path_constraint: true
*/
//'image_path_constraint' => false,
/**
* Set default timezone.
*
* Default values.
* default_timezone: ini_get('default_timezone') or 'UTC'
*/
//'default_timezone' => 'UTC',
@@ -69,9 +112,12 @@ return array(
* This is basically a security constraint to avoid using resources on creating
* large (unwanted) images.
*
* Default values.
* max_width: 2000
* max_height: 2000
*/
'max_width' => 2000,
'max_height' => 2000,
//'max_width' => 2000,
//'max_height' => 2000,
@@ -83,6 +129,8 @@ return array(
* the alpha value is between 00 (opaqe) and 7F (transparent),
* that is between 00000000-FFFFFF7F.
*
* Default values.
* background_color: As specified by CImage
*/
//'background_color' => "FFFFFF",
//'background_color' => "FFFFFF7F",
@@ -92,7 +140,19 @@ return array(
/**
* Post processing of images using external tools, set to true or false
* and set command to be executed.
*
* Default values.
*
* png_filter: false
* png_filter_cmd: '/usr/local/bin/optipng -q'
*
* png_deflate: false
* png_deflate_cmd: '/usr/local/bin/pngout -q'
*
* jpeg_optimize: false
* jpeg_optimize_cmd: '/usr/local/bin/jpegtran -copy none -optimize'
*/
/*
'postprocessing' => array(
'png_filter' => false,
'png_filter_cmd' => '/usr/local/bin/optipng -q',
@@ -103,26 +163,59 @@ return array(
'jpeg_optimize' => false,
'jpeg_optimize_cmd' => '/usr/local/bin/jpegtran -copy none -optimize',
),
*/
/**
* Create custom convolution expressions, matrix 3x3, divisor and
* offset.
*
* Default values.
* convolution_constant: array()
*/
/*
'convolution_constant' => array(
//'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',
),
*/
/**
* Prevent leeching of images by controlling who can access them from where.
* Default it to allow hotlinking.
* Password apply when hotlinking is disallowed, use password to allow.
* The whitelist is an array of regexpes for allowed hostnames that can
* hotlink images.
*
* Default values.
* allow_hotlinking: true
* hotlinking_whitelist: array()
*/
/*
'allow_hotlinking' => false,
'hotlinking_whitelist' => array(
'#^localhost$#',
'#^dbwebb\.se$#',
),
*/
/**
* Create custom shortcuts for more advanced expressions.
*
* Default values.
* shortcut: array(
* 'sepia' => "&f=grayscale&f0=brightness,-10&f1=contrast,-20&f2=colorize,120,60,0,0&sharpen",
* )
*/
/*
'shortcut' => array(
'sepia' => "&f=grayscale&f0=brightness,-10&f1=contrast,-20&f2=colorize,120,60,0,0&sharpen",
),
),*/
@@ -137,7 +230,11 @@ return array(
* &width=w1 // results in width=613
* &width=c2 // results in spanning two columns with a gutter, 30*2+10=70
* &width=c24 // results in spanning whole grid 24*30+((24-1)*10)=950
*
* Default values.
* size_constant: As specified by the function below.
*/
/*
'size_constant' => function () {
// Set sizes to map constant to value, easier to use with width or height
@@ -156,15 +253,17 @@ return array(
}
return $sizes;
},
},*/
/**
* Predefined aspect ratios.
*
* Default values.
* aspect_ratio_constant: As the function below.
*/
'aspect_ratio_constant' => function () {
/*'aspect_ratio_constant' => function () {
return array(
'3:1' => 3/1,
'3:2' => 3/2,
@@ -174,20 +273,5 @@ return array(
'16:9' => 16/9,
'golden' => 1.618,
);
},
/**
* Set error reporting to match development or production environment
*/
'error_reporting' => function () {
error_reporting(-1); // Report all type of errors
ini_set('display_errors', 1); // Display all errors
set_time_limit(20);
ini_set('gd.jpeg_ignore_warning', 1); // Ignore warning of corrupt jpegs
if (!extension_loaded('gd')) {
throw new Exception("Extension gd is nod loaded.");
}
},
},*/
);

35
webroot/img_header.php Normal file
View File

@@ -0,0 +1,35 @@
<?php
/**
* Resize and crop images on the fly, store generated images in a cache.
*
* This version is a all-in-one version of img.php, it is not dependant an any other file
* so you can simply copy it to any place you want it.
*
* @author Mikael Roos mos@dbwebb.se
* @example http://dbwebb.se/opensource/cimage
* @link https://github.com/mosbth/cimage
*
*/
/**
* Change configuration details in the array below or create a separate file
* where you store the configuration details.
*
* The configuration file should be named the same name as this file and then
* add '_config.php'. If this file is named 'img.php' then name the
* config file should be named 'img_config.php'.
*
* The settings below are only a few of the available ones. Check the file in
* webroot/img_config.php for a complete list of configuration options.
*/
$config = array(
//'mode' => 'production', // 'production', 'development', 'strict'
//'image_path' => __DIR__ . '/img/',
//'cache_path' => __DIR__ . '/../cache/',
//'alias_path' => __DIR__ . '/img/alias/',
//'remote_allow' => true,
//'password' => false, // "secret-password",
);

3918
webroot/imgd.php Normal file

File diff suppressed because it is too large Load Diff

3918
webroot/imgp.php Normal file

File diff suppressed because it is too large Load Diff

3918
webroot/imgs.php Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -17,11 +17,13 @@ $description = "The issue was to implement fill-to-fit, but it needs some flexib
// Use these images in the test
$images = array(
'kodim04.png',
'apple_trans.gif',
'circle_trans.png',
);
// For each image, apply these testcases
// For each image, apply these testcases
$cache = "&nc"; // ""; // "&nc"
$testcase = array(
"$cache&w=300&h=300&fill-to-fit",