PHPImageHandler - Handling images in PHP

A small PHP library to manage your images, automatically create thumbnails and custom size images.

Simplify your PHP project by adding this awesome image handler library.

PHPImageHandler is your escape from writing your own image handling in custom PHP code. It has all the necessary features to handle your images, serve as the base for any gallery and simplify your life.

It is easy as cooking a pie :)

Just include the autoloader

include_once('[path to Image handler]/autoload.php');

Initialize the class. Note that PHPImageHandler loads the config from its source folder from the file named config.php, but you can overwrite the options from initialization, too, like

$imageHandler = new ImageHandler(
    array(
        'sizes' => array(
            'normal' => array('width' => 50, 'height' => 50)
        ),
        'db' => array(
            'server' => 'localhost',
            'user' => 'root',
            'pass' => '',
            'database' => 'test',
            'table_name' => 'images'
        ),
        'base_path' => dirname(__FILE__) . DIRECTORY_SEPARATOR . 'test_images'
    )
);

This step is optional, but it is good to have. Checks if storage exists and creates it if not

if ( !$imageHandler->storage_exists() )
{
    $imageHandler->install_storage();
}

Now all is set, you can start coding.

Checking an uploaded image for errors and saving:

if ( array_key_exists('image', $_FILES) )
    {
        // Validate and save image
        if ( $imageHandler->validate_image($_FILES['image']) )
        {
            $imageHandler->save_image($_FILES['image'], 1, 'test', 'test_images/1');
        }
        else
        {
            var_dump($imageHandler->get_errors());
        }
    }

Get an image:

$images = $imageHandler->get_image_by(array('object_id' => 1, 'object_type' => 'test'));

Delete an image:

$imageHandler->delete_image_by(array('object_id' => 1, 'object_type' => 'test'));

For the people who just want to get started right away.

Firstly set the config, here is a commented config section for you to understand:

	array(
		'db' => array( // DB Config for DB storage
			'server' => '', // Host you want to connect to, like localhost
			'user' => '', // DB user
			'pass' => '', // DB password
			'database' => '', // Name of the database
			'table_name' => 'images' // Name of the table you want to save the images to
		),
		'sizes' => array( // The array with the sizes you want to use, original size is also saved
			'normal' => array( 'width' => 250, 'height' => 250 ), // HAS TO EXIST, this is the base that we compare to, so use this as the smallest size to compare to
			'thumbnail' => array('width' => 50, 'height' => 50)
		),
		'validate_base_size' => true, // If true, compares uploaded image size to the sizes of "normal", throws error if image is smaller
		'is_crop' => true, // If true, crops the image to the given size instead of just resizing 
		'max_upload_size' => 5242880, // The maximum upload size in BYTES
		'base_path' => '' // Base path for images in the folder structure
	);

You can use the code provided in the package in index.php

	// DO NOT FORGET TO SET THE CONFIG FILE
	include_once('src/autoload.php');
	
	$imageHandler = new ImageHandler();
	
	if ( !$imageHandler->storage_exists() )
    {
        $imageHandler->install_storage();
    }
	
	$error = '';
	// Handle POST
	if ( $_POST )
	{	
		if ( array_key_exists('image', $_FILES) )
		{
			// Validate and save image
			if ( $imageHandler->validate_image($_FILES['image']) )
			{
				// In this example we always have one image, so we delete the old one
				$imageHandler->delete_image_by(array('object_id' => 1, 'object_type' => 'test'));
				
				// Save the new one
				$imageHandler->save_image($_FILES['image'], 1, 'test', 'test_images/1');
			}
			else
			{
				$errors = $imageHandler->get_errors();
				$error = reset($errors);
			}
		}
	}

This is for more experienced programmers.

PHPImageHandler is built using modules that can be changed. For example if you want to change the way PHPImageHandler saves data about an image, you can write your own storage class. It must implement the storage interface. After writing it, you can just pass it to the constructor.

The same goes for the validator class, if you want to change the way images are validated.

class MyCustomStorageClass implements StorageInterface
class MyCustomImageValidation implements ValidationInterface

Also, you can have multiple instances with different configs passed, thus being able to handle all kinds of situations you want.

This is for the users who want to totally customize their code using PHPImageHandler.

The PHPDoc sections contain examples you can use to understand the functionality.

/**
 * Constructor.
 * @param array $config Can overwrite default config upon creation
 * If no storage class is provided, the config default will be used
 * @param ServerMessage\Interfaces\Storage $storage
 * @param ServerMessage\Interfaces\Validation $validation The validation class that validates the message, can be set externally
 */
public function __construct(Array $config = array(), StorageInterface $storage = null, ValidationInterface $validation = null)

/**
 * Gets an image based on given parameters
 * Examples:
 *     get images belonging to one type, for example dogs
 *     get_image_by(array('object_type' => 'dogs'));
 *        get the original of an image
 *     get_image_by(array('object_type' => 'dogs', 'object_id' => 1), 'original')
 * @param array $params The array containing the things you want to compare by
 * @param string $compare_name OPTIONAL If set, it compares the name of the image to this string
 * @return array
 */
public function get_image_by(Array $params, $compare_name = null)

/**
 * Validates the incoming image
 * It checks if the image is actually an image and if all things are ok with it
 * @param array $image This is the image array from $_FILES, like $_FILES['image1']
 * @return boolean
 */
public function validate_image($image)

/**
 * Saves an image to file structure and storage
 * The original image is always saved first and then the sizes from config
 * The image saving is based on objects for example a saved image belongs to a dog object
 * @param array $image The image array from $_FILES
 * @param int $object_id The id of the object the image belongs to, for example dog id number 1
 * @param string $object_type The type of object the image belongs to, like "dogs"
 * @param string $path The path the image is saved to, this will be appended to base url from config,
 * for example BASE_PATH/dogs/[dog_id] will save the original and cropped images into this folder
 * it creates the folder structure automatically if does not exist
 * @param mixed $meta Here you can pass an array, a string, anything you want, it will be serialized and encoded
 * @return null
 */
public function save_image($image, $object_id, $object_type, $path, $meta = null)

/**
 * Deletes an image by given parameters
 * @param array $params This is the associative array with the params
 * Example: you want to delete the images belonging to dog number one
 *     delete_image_by(array('object_id' => 1, 'object_type' => 'dogs'))
 * @return void
 */
public function delete_image_by(Array $params)

/**
 * Checks if storage exists
 * @return boolean
 */
public function storage_exists()

/**
 * Creates storage if that does not exist
 */
public function install_storage()

/**
 * Clear out the storage created
 * WARNING: Deletes all data in storage, too, if not otherwise implemented
 */
public function remove_storage()

/**
 * Returns the errors happening during image manipulation
 * @return array
 */
public function get_errors()

/**
 * Returns the base path set in config
 * @return string
 */
public function base_path()