Stefan Gabos web developer extraordinaire
Zebra_Image, a lightweight image manipulation library written in PHP
-
Latest version2.2.2released onAugust 31, 2012
- 1. Overview
- 2. Features
- 3. Requirements
- 4. Installation
- 5. How to use
- 6. Download
- 7. Documentation
- 8. Changelog
- 9. Comments
This is a compact (one-file only), lightweight, object-oriented image manipulation library written in and for PHP, that provides methods for performing several types of image manipulation operations. It doesn’t require any external libraries other than the GD2 extension (with which PHP usually comes pre-compiled with).
With this library you can resize, flip, rotate , crop and sharpen images. All sort of filters can also be applied to images: negate, grayscale, brightness, contrast, colorize, edgedetect, emboss, gaussian blur, selective blur, mean removal, smooth and pixelate; multiple filters can be applied at once for creating custom filters; It supports loading and saving images in the GIF, JPEG and PNG formats and preserves transparency of GIF, PNG8 and PNG24 images.
Zebra_Image‘s code is heavily commented and generates no warnings/errors/notices when PHP’s error reporting level is set to E_ALL.
The cool thing about it is that it can re-size images to exact given width and height and still maintain aspect ratio by using one of the following methods:
- the image will be scaled so that it will fit in a box with the given width and height and then it will be centered both horizontally and vertically in the box. The blank area will be filled with a specified color.
- the image will be scaled so that it could fit in a box with the given width and height but will not be enclosed in a box with given width and height
- after the image has been scaled so that its width and height are equal or greater than the required width and height respectively, a region of required width and height will be cropped from the top left corner of the resulted image.
- after the image has been scaled so that its width and height are equal or greater than the required width and height respectively, a region of required width and height will be cropped from the center of the resulted image.
Here are the results of resizing a 800×573 pixels image to a 200×200 pixels image and preserving the aspect ratio by using each of the aforementioned methods:
|
|
Method 1 |
|
|
Method 2 |
|
|
|
Method 3 & 4 |
|
|
|
Step 2: A 200×200 pixels area will be cropped from the top-left corner of the image (for method 3) or from the center of the image (for method 4). |
|
Features review
- can be used to resize, flip, rotate, crop and sharpen images
- filters can be applied to images: negate, grayscale, brightness, contrast, colorize, edgedetect, emboss, gaussian blur, selective blur, mean removal, smooth and pixelate; multiple filters can be applied at once for creating custom filters;
- can resize images to *exact* size by automatically cropping them
- preserves transparency of GIF, PNG8 and PNG24 images
- code is heavily commented and generates no warnings/errors/notices when PHP’s error reporting level is set to E_ALL
- has comprehensive documentation
Requirements
PHP 4.4.9+ (PHP 5+ for using filters), bundled GD 2.0.28+
Installation
Download the latest version, unpack it, and put it in a place accessible to your scripts.
How to use
<?php
// load the image manipulation class
require 'path/to/Zebra_Image.php';
// create a new instance of the class
$image = new Zebra_Image();
// indicate a source image (a GIF, PNG or JPEG file)
$image->source_path = 'path/to/image.png';
// indicate a target image
// note that there's no extra property to set in order to specify the target
// image's type -simply by writing '.jpg' as extension will instruct the script
// to create a 'jpg' file
$image->target_path = 'path/to/image.jpg';
// since in this example we're going to have a jpeg file, let's set the output
// image's quality
$image->jpeg_quality = 100;
// some additional properties that can be set
// read about them in the documentation
$image->preserve_aspect_ratio = true;
$image->enlarge_smaller_images = true;
$image->preserve_time = true;
// resize the image to exactly 100x100 pixels by using the "crop from center" method
// (read more in the overview section or in the documentation)
// and if there is an error, check what the error is about
if (!$image->resize(100, 100, ZEBRA_IMAGE_CROP_CENTER)) {
// if there was an error, let's see what the error is about
switch ($image->error) {
case 1:
echo 'Source file could not be found!';
break;
case 2:
echo 'Source file is not readable!';
break;
case 3:
echo 'Could not write target file!';
break;
case 4:
echo 'Unsupported source file format!';
break;
case 5:
echo 'Unsupported target file format!';
break;
case 6:
echo 'GD library version does not support target file format!';
break;
case 7:
echo 'GD library is not installed!';
break;
}
// if no errors
} else {
echo 'Success!';
}
?>
Download
Zebra_Image is distributed under the LGPL.
In plain English, this means that you have the right to view and to modify the source code of this software, but if you modify and distribute it, you are required to license your copy under a LGPL-compatible license, and to make the entire source code of your derivation available to anybody you distribute the software to.
You also have the right to use this software together with software thas has different licensing terms (including, but not limited to, commercial and closed-source software), and distribute the combined software, as long as state that your software contains portions licensed under the LGPL license, and provide information about where the LGPL licensed software can be downloaded.
If you distribute copies of this software you may not change the copyright or license of this software.
You may also like:
- Zebra_cURL, a a high performance PHP cURL library
- Zebra_Database, a MySQL database wrapper written in PHP
- Zebra_Form, a jQuery augmented PHP library for creating and validating forms
- Zebra_Image, a lightweight image manipulation library written in PHP
- Zebra_Mptt, a PHP implementation of the modified preorder tree traversal algorithm
- Zebra_Pagination, a generic pagination class written in PHP
- Zebra_Session, a wrapper for PHP's default session handling functions, using MySQL for storage
Documentation
|
Become a ninja. Read the comprehensive documentation. |
Changelog
Click on a version to expand/collapse information.
- version 2.2.2 (August 31, 2012)
-
- fixed a bug where if there were no disabled PHP functions (through php.ini), the library would always return error code 8; thanks to Jim Li;
- filters can now be applied to images; the existing filters are those handled by PHP’s imagefilter function: negate, grayscale, brightness, contrast, colorize, edgedetect, emboss, gaussian blur, selective blur, mean removal, smooth and pixelate; multiple filters can be applied at once for creating custom filters;
- version 2.2.1 (September 09, 2011)
-
- fixed two bugs that appeared since the last version that would cause the script to throw warnings; thanks to NIXin for reporting;
- version 2.2 (September 06, 2011)
-
- a new property is now available: png_compression, which determines the compression level of PNG files; this value of this property is ignored for PHP versions older than 5.1.2; thanks to Julien for suggesting;
- a new property is now available: sharpen_images which, when enabled, will instruct the script to apply a “sharpen” filter to the resulting images; can be very useful when creating thumbnails but should be used only when creating thumbnails; the sharpen filter relies on PHP’s imageconvolution function which is available only for PHP version 5.1.0+, and will leave the images unaltered for older versions;
- added new cropping options: TOPCENTER, TOPRIGHT, MIDDLELEFT, MIDDLERIGHT, BOTTOMLEFT, BOTTOMCENTER, BOTTOMRIGHT; thanks to flam for suggesting;
- entire logic behind the resize method was rewritten;
- fixed a bug where the script would generate warnings if the chmod function was disabled via PHP configuration options; now it will not generate the warning but instead will set a value for the script’s error property;
- fixed a bug where if one would resize a transparent image and in the process would convert it to a JPEG (no transparency) and the resize method’s background_color argument was set to -1, the resulted image’s background color would be black; now it is white, as described in the documentation; thanks to Julien for reporting;
- version 2.1.2 (May 09, 2011)
-
- fixed a bug when resizing images having height greater than width, and using the resize() method with only the height argument; thanks to Manuweb2 for reporting.
- version 2.1.1 (March 24, 2011)
-
- fixed a bug where the script would produce warnings on some particular transparent GIF images; thanks to Olof Fredriksson for reporting.
- version 2.1 (February 05, 2011)
-
- fixed a bug where the script would produce warnings on partially broken JPEG files and would not process the image; now the script will successfully handle such images;
- fixed a bug where the rotate method was not working correctly on transparent PNG/GIF images;
- improved overall handling of transparent images;
- a new method was added: “flip_both” which flips an image both vertically and horizontally;
- the code for flip_horizontal and flip_vertical methods was rewritten;
- a more explicit example was added;
- version 2.0 (September 27, 2010)
-
- entire code was audited and improved;
- method names, method arguments and global properties were changed and therefore this version breaks compatibility with previous ones;
- resize() method was improved and now can resize an image to exact width and height and still maintain the aspect ratio by involving the crop() method;
- fixed a bug where the crop(), flip_horizontal() and flip_vertical() were not working correctly for transparent PNG files;
- some documentation refinements;
- version 1.0.5 (August 23, 2007)
-
- fixed a bug where the resize() method would produce unexpected results when the actual width of the image was smaller than the value of the resizeToWidth property and resizeIfSmaller property was set to FALSE. in this case, if the height of the image was to be adjusted upwards, the width of the image was increased indefinitely not taking in account the value of resizeToWidth property;
- version 1.0.4 (October 13, 2006)
-
- a new method was added – crop();
- a new property was added – preserveSourceFileTime which is by default set to TRUE and which instructs the scripts to preserve the date/time of the source files and pass it on to the target files; thanks to patrick from swederland;
- the flip_horizontal and flip_vertical methods were stil using the imagecopy function instead of using the imagecopyresampled function;
- the create_image_from_source_file() function was incorrectly checking for the existence of the source file: you could specify a valid path (but not a file) and the script would crash error because the path indeed existed even though it was not a file;
- the result of the create_image_from_source_file() private method was poorly implemented and the script could be easily crashed by specifying bogus source files;
- version 1.0.3 (September 13, 2006)
-
- if invalid sizes were specified for resizing (i.e. string or negative numbers) the script would crash;
- resizing of transparent png24 files was not working; thanks mar251;
- working with png files would always make the value of the “error” property equal to 5 even if everything went well;
- when resizing, interpolation was not used and the resulting images were rough. now imagecopyresampled function is used instead of imagecopyresized; thanks Sabri;
- resizing was not working correctly in some cases;
- version 1.0.2 (August 12, 2006)
-
- error checking for the source file was incorrectly implemented and the script would produce warnings and fatal errors if there were problems with the source file;
- properties will now have default values in PHP 4;
- version 1.0.1 (August 11, 2006)
-
- after output, the file was chmod-ed incorrectly;
- the documentation now tells you about how to calculate the permission levels;
- version 1.0 (August 04, 2006)
-
- initial release;









I am a 32 year old web developer working from Bucharest, Romania. I am coding since I was 14 and I am extremely passionate about it. For the server side of things I use PHP/MySQL while on the front-end I write valid HTML 5, nice CSS and lots of JavaScript code using jQuery.
Zebra_Image has been featured at LinuxLinks.com
ReplyHi,
Thanks for the great and useful library/utility code.
Is there a reason why you released it as GPL? This sort of excludes it from use in commercial purposes, since GPL code can only be used with other GPL code. If that is your intent, then I respect it.
However if you think that you want contribution and allow commercial use, may I recommend the LGPL license since that is more appropriate for libraries and utility classes.
Sincerely,
Tri Bui
Replyyou are right, i’ll update the license to LGPL. thanks!
Hmm, yet another 20K wrapper for GD image resizing, with a cumbersome API, released under the GNU GPL (instead of the LGPL as advertised in the license.txt – or any other appropriate library license), and you are still asking for donations??
ReplyZebra_Image, a lightweight image manipulation library written in PHP…
A compact, lightweight, object-oriented image manipulation library written in and for PHP, that provides methods for performing several types of image manipulation operations. It doesn’t require any external libraries other than the GD2 extension (with…
ReplyReally nice script!
But.. when trying resize gif-images i get this error:
Warning: imagecolorsforindex() [function.imagecolorsforindex]: Color index 255 out of range in /home/XYXYXYXYX/domains/domain.com/public_html/zebra/Zebra_Image.php on line 843
I am using the example code that are included in the download package. Bug?
ReplyCan you please email me an image that generates this error? I might have found a fix for it, but I need a transparent GIF with which I can reproduce the error – I’ve created some transparent GIFs myself but couldn’t reproduce. Thanks!
Hi everyone,
After searching on hour for a problem of resize when image height > width and using the resize function with only the height arguement, i’ve figured ou that there is an error in the script line 423 :
replace $this->this->source_width <= source_height ?
by $this->source_width <= source_height ?
Copy/paste error from the developer
Thank you for this amazing script !
ReplyManu
indeed there was a typo – thank you for letting me know! the new version is now patched and available for download.
Wow, thx for the tut, I’ll be happly giving you credit back to this site
ReplyHi,
Your script is perfect!!
Thank you very much for sharing it
ReplyThank you for taking the time to write back and I am glad you found the script useful.
Hi, thanks for this class, do you think it’s possible to add a method for crop bottom ? thanks.
Replyyes, it is possible. until a new version will be available you can hack the code in Zebra_Image.php, starting at line 586. there are comments that should help you.
This is great, a simple class that just does the right things and not 1000 other useless things. Thanks !
However I have a little request. You allow jpeg quality config, which is ok. But would it also be possible for you to add a PNG quality setting, so that the png outputs can be smaller ? Could be great.
Also, it would sometimes be nice to be able to remove png transparency. Let’s say I want to save a PNG to JPG…then the background is black at the moment, which is not good. I’d like to be able to set it to white in this case. Again, would it be possible ?
Anyways, thanks !
ReplyThanks Julien, your requests make perfect sense (I have no idea why there isn’t an option for setting the compression level for PNG files) and I’ll add them as soon as possible. Maybe a week, or so…
Thanks a lot!
Usefull script. Thanks for it.
however I have a problem : I try to resize with ZEBRA_IMAGE_BOXED method with width greater than height. If original image is larger than high, result is croped… bug?
ReplyHi
I’m getting a notice with the latest version:
Notice: Undefined variable: background in vendor/Zebra_Image.php on line 669
PS
ReplyYour captcha is horrible and totally unreadable. I had to try two times, and every time copy and paste the content of my comment…
Hi, sorry about double comment, but I get one more warning. If there are no disabled functions in php.ini, this happens:
Warning: strpos() [function.strpos]: Empty delimiter in /vendor/Zebra_Image.php on line 1496
I fixed the first notice by removing the unused variable $background.
Here’s a quick fix for the other one:
Replyif (strlen(ini_get('disable_functions') > 0) && strpos('chmod', @ini_get('disable_functions')) === false) {Sorry for third message in a row.
ReplyActually just silencing the strpos is enough.
So,
if (@strpos('chmod', @ini_get('disable_functions')) === false) {works well.thanks for reporting! the patched version, fixing both of the aforementioned bugs, is available for download.
what about resizing animated gif?
Replyhmmm…never thought of that
i’ll see what i can do
I am very expect this feature.