Atilla Ördög

Personal site of Atilla Ördög AKA Gadratil

Tag: image

PHP Image Handler

I wrote about the image handling library I made. The small code snippet I wrote was poor and hard to understand.

I optimized the code and created example and documentation for my Image Handler PHP library.

Now it can be found on Gadratil Programming in the shop section.

Make your life easier using this library by adding it to any custom framework or CMS.

PHP Image Handler

 

Advertisements

ImageHandler, a small and useful tool

Usually every CMS and Framework has its own image handling class. The problem is between, however, because in a CMS image handling is part of a media library that is big and complex.

In a Framework image handling is not done at all, it just has some classes for helping the developer.

This gap is what I tried to fill by creating a small tool for handling images.

This tool is very lightweight, easy to use and covers a large area in image handling.

It is created in a way that a developer can easily change the storage and validation classes if needed. Currently data is saved into DB using Mysqli and validation checks basic aspects.

Configuration can be passed using the Config class and the config file in the base folder, but config params can be passed upon initialization, too.

The image handling is done by Kohana`s Image library, surely it is a bit modified to fit my needs. This tool uses GD or Imagick library, so you will have to enable that if you want to handle images.

What you will need to run this code: PHP 5+, mysqli, GD or Imagick

Here is a full sample of the usage of this library

include_once('ImageHandler/autoload.php');

// Initialize the class, it loads config from the config file, but configs can be overwritten from here
$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'
)
);

// Check if storage exists and create it if does not
if ( !$imageHandler->storage_exists() )
{
$imageHandler->install_storage();
}

// Check if we have to delete
if ( array_key_exists('delete_image', $_GET) )
{
$imageHandler->delete_image_by(array('object_id' => 1, 'object_type' => 'test'));
}

// Handle POST
if ( $_POST )
{
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());
}
}
}

echo 'Current image:';

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

var_dump($images);

You can find this library here: https://github.com/atillaordog/ImageHandler