Zebra_Image, a lightweight image manipulation library written in PHP

Get the latest updates on this PHP library via RSS

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:

  1. 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.
  2. 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
  3. 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.
  4. 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:

Zebra_Image, Example 1
Image by Laughing Squid

Method 1
After the image is resized to 200×143 pixels – representing the size of the image that would fit in a 200×200 pixels box while preserving its aspect ratio, it is centered both horizontally and vertically in a
200×200 pixels box, having a predefined background – white, in our example. The resulting image has 200×200 pixels.

Example 2

Method 2
The image is resized to 200×143 pixels – representing the size of the image that would fit in a 200×200 pixels box while preserving its aspect ratio.

Example 3

Method 3 & 4
Step 1: The image is first resized to 279×200 pixels – representing the size closest to the required size where the image’s width and height are both equal or greater than the required width and
height respectively, while preserving its aspect ratio.

Example 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).

Example 5

Top

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

Top

Requirements

PHP 4.4.9+ (PHP 5+ for using filters), bundled GD 2.0.28+

Top

Installation

Download the latest version, unpack it, and put it in a place accessible to your scripts.

Top

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!';

    }

?>

Top

Download

version 2.2.3
If you find this library to be useful to you, you can support the author by donating a small amount via PayPal:

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 that 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:

Top

Documentation

Documentation Become a ninja.
Read the comprehensive documentation.

Top

Changelog

Click on a version to expand/collapse information.

version 2.2.3 (July 14, 2013)
  • removed the error muting used for imagecreatefrom{gif,jpeg,png} calls in the “_create_from_source” private method, which would cause the script to silently fail if the memory limit was exceeded; thanks to Eren Türkay;
  • project is now available on GitHub and as a package for Composer
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;

Top

79 responses to “Zebra_Image, a lightweight image manipulation library written in PHP”

Follow the comments via RSS
  • jacob lee, 2012-10-06, 10:07

    Could you show me the easy way to have watermark on image?
    Thanks in advance.

    Reply
  • Brian H., 2012-10-29, 21:21

    I keep coming back to this library, as it’s the best one I’ve found for modifying and saving uploaded images. Has it ever been configured to be used in CodeIgniter?

    Reply
    • Stefan Gabos, 2012-10-29, 21:23

      not that I know of…but it’s as standalone as it gets :) so it should be fairly easy to be used with any framework

  • Bastian, 2013-01-16, 19:25

    Thanks you for this great library. I have one question, when I resize a file, it does not overwrite an already existing (resized) image. Do you know of this?

    Reply
    • Stefan Gabos, 2013-01-16, 19:30

      are you setting the proper permissions to the image?

    • Bastian, 2013-01-16, 19:35

      I’m running XAMPP (test server) on Windows 7. So i’ll guess that permissions do not matter. I tried adding unlink() to the script. But then I get a permission denied error.

    • Stefan Gabos, 2013-01-16, 19:46

      strange…I am using something similar WAMP on Windows 7 and it’s working…

    • Bastian, 2013-01-16, 19:44

      Btw. i get error 3: ‘Could not write target file!’

  • Bastian, 2013-01-16, 20:08

    Solved. I had to do this at the top of function _write_image()

    chmod($this->target_path, 0777);
    unlink($this->target_path);

    This is only for Windows, because on my webserver, the permissions are already 777

    Reply
  • Malik, 2013-01-24, 21:02

    This is one easy to use library, man I cant believe how easy it was to use this. Keep up the good work. No! Keep up the great work. All the best

    Reply
    • Stefan Gabos, 2013-01-26, 11:18

      thank you!

  • Eren Türkay, 2013-02-07, 03:34

    Thank you for such a beatiful and well-written library! It couldn’t be more easier to use it. I had one issue with silented errors and I debugged the problem. It would be better to inform the users about a possible error (related with bigger image resolutions such as 2560×1600).

    Please see my stackoverflow reply for it.

    http://stackoverflow.com/questions/4590441/php-thumbnail-image-resizing-with-proportions/14743045#14743045

    My best regards,
    Eren

    Reply
    • Stefan Gabos, 2013-02-07, 08:12

      thank you! i’ll have a look and correct that

  • Bartek, 2013-02-27, 11:38

    Are you planning to make it possible to add watermarks to animated gifs? Is it possible with some libraries, but when I do it using Zebra Image gifs don’t move.

    Reply
    • Stefan Gabos, 2013-02-27, 14:01

      it’s not possible at all to add watermarks to images with Zebra_Images, nor is this planned

  • mrapp, 2013-03-25, 13:45

    When $img->source_path is $_FILES['upl_image']['tmp_name'], then i can only manipulate i only one time.

    $img->source_path = $_FILES['upl_image']['tmp_name'];
    $img->target_path = ‘nename.jpg’;
    $img->resize(600, 0, ZEBRA_IMAGE_CROP_CENTER); // working

    $img->target_path = ‘secondname.jpg’;
    $img->resize(150, 0, ZEBRA_IMAGE_CROP_CENTER); // not working

    Reply
    • Stefan Gabos, 2013-03-25, 17:53

      it’s probably because PHP’s garbage collector kicks in (as the file is in the temporary directory and would be removed by the time the script ends, but for some reason you trigger this behaviour because you “touch” the file)
      i always first move uploaded files to a safe spot and then do the work

  • Benny, 2013-04-18, 10:29

    Hello,

    i try using this. i have a problem:
    my image has a large height, the width is smale. i uploaded the image to the server first and start than the resize.
    my original big image is ok, the thumbnail is rotate to the left site so that width is now larger than height.

    any idea why? can i disable this?

    Reply
    • Stefan Gabos, 2013-04-23, 05:51

      can you please email me the code you are using along with the image?

  • Bman, 2013-05-21, 21:16

    Thanks much for this great script ! it’s exactly what I was looking for.

    I can create individual images OK.. but how can I process multiple images at once with the same filter ? like coloring 10 images at once after changing a one variable to black color for example ?

    Thanks again

    Reply
    • Stefan Gabos, 2013-05-22, 06:36

      using a for-each?

  • Christian Bocaz, 2013-08-01, 03:21

    Hi, thanks for this great image library.
    I use xampp over win7.
    My php.ini have a memory_limit = 128M.
    But when I run this script, I get this error: Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 4320 bytes) in A:\xampp\htdocs\temp\Zebra_Image.php on line 1272

    My cript is:

    require 'Zebra_Image.php';
      $image = new Zebra_Image();
    
      $bigsize = 800;
      $smallsize=150;
    
      $image->preserve_aspect_ratio = true;
      $image->enlarge_smaller_images = true;
      $image->jpeg_quality = 100;
      $image->preserve_time = true;
    
      $image->source_path = 'image.jpg';
      $image->target_path = 'image_small.jpg';
      $image->resize(0, $smallsize, ZEBRA_IMAGE_CROP_CENTER);
    
      $image->target_path = 'image_big.jpg';
      $image->resize(0, $bigsize, ZEBRA_IMAGE_CROP_CENTER);
    Reply
    • Christian Bocaz, 2013-08-01, 03:38

      sorry, and the original image size is 3.472kb

  • Christian Bocaz, 2013-08-01, 05:33

    Solved: the upload_max_filesize must be bigger than image sizes or we need to evaluate the image size before

    Reply
  • kisay, 2013-08-02, 11:25

    thanks for your shares!
    thanks for google takes me here.

    a php beginer from china.

    Reply
  • Daniel, 2013-09-30, 20:38

    Just wanted to say thanks for this great library. I use it and love it. Even a novice PHP developer like myself figured it out. Thanks for the great work & documentation.

    Reply
    • Stefan Gabos, 2013-09-30, 20:54

      As Nick Cave once said: “No man, thank *You*!” :)

  • Helge, 2014-03-21, 12:18

    Hi!

    Great libraray. But i missed a feature. It is possible to get an image with a fixed size of 100×100 form a given image with a size of 70×50 and the image is not scaled up? So i have an image with 100×100 with centered source image.
    This works perfect with images greater than the size of 100×100

    Reply
    • Stefan Gabos, 2014-03-22, 19:17

      how can we have a 100×100 image from 70×50 without scaling it up?

    • Helge, 2014-03-24, 11:18

      Hi!

      you have to center it in the middle like the funktion far from phpthump (leave original size)

Leave a Reply

Your email address will not be published
You can use <strong>, <em>, <a>, <img>, <code>
Characters are not case-sensitive