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

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

Follow the comments via RSS
  • Mr. Jesux, 2014-04-10, 04:41

    Hi, I’m newbie and I would like to know some things. I hope you can assist me.

    How it applied to gray scale effect, since it fits where I get to gray but the effect does not respect the image dimensions, or place the image in full color and sizes respects.

    I would like to know where in the judgment put you apply the color to gray scale?

    $image->source_path = $file;
    $image->target_path = $path_new."/".$image_name."_magazine@X1.".$image_ext;
    $image->apply_filter('grayscale');
    $image->resize(220, 157, ZEBRA_IMAGE_CROP_CENTER);
    Reply
    • Stefan Gabos, 2014-05-19, 19:46

      that is happening because all the library’s methods work on the source file. so, you are first applying the filter to the source file and save it with a different name, and then you are resizing the source file and save it with the same name, overwriting the previous one. the solution is

      $output = $path_new . '/' . $image_name . '_magazine@X1.' . $image_ext;
      
      $image->source_path = $file;
      $image->target_path = $output;
      
      $image->apply_filter('grayscale');
      
      // make sure we're working on the new, grayscale, image
      $image->source_path = $output;
      $image->resize(220, 157, ZEBRA_IMAGE_CROP_CENTER);

Leave a Reply

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