Ecommerce Developer
 
 

Code

Examples of Automated Image Manipulation in PHP

 

Images are an important aspect of any website. As they say, an image is worth a 1,000 words. In ecommerce websites, we use images to represent products to customers in the hope that those images will increase sales.

With so much riding on the success of a product image, it is little wonder that clients often want more than one product image on a product detail page. And, often, those diverse images need to come in different shapes and sizes. To help administer all of these potential product images, it would be great to have an administrator panel where we could upload, resize, watermark, or rotate our images.

CodeIgniter has a very good image manipulation class built-in that can do resizing, cropping, rotations, watermarking, and thumbnail creation. With just a few lines of code you can process images in ways that otherwise would take much more time. The class documentation for all of this wonderful image manipulation can be found on the CodeIgniter site.

Resizing Images

Thumbnails can be created in several ways. I will mention two.

The thumbnails and other resized images can be created automatically when the image is uploaded. For this you will need to know where you will need them and what sizes they will have.

For example, imagine that we need to create an image resizing system for an ecommerce website that we're developing for a client. We will have three types of images; thumbnails for categories, small images for product category pages, and full-sized images for product detail pages. In this scenario, a user or administrator uploads an image that is 800 x 600, and calls it sample1.jpg. The system creates a thumbnail which is 100 x 75 and sets a file name, thumb1.jpg. Next, the system creates a small version of the image of 300 x 200, normal_1.jpg. And finally we have the system upload all of the images. In CodeIgniter we load the images like <?php echo img('uploads/normal_1.jpg'); ?>.

Not bad, right? But the downside to this solution is that if you want to change the sizes of the thumbnails or small images the next time the site gets a redesign, you need to delete all the thumbnails and recreate them.

A second solution fixes the problem. In this scenario, am image is uploaded normally and the thumbnails are created only when the page that requires them is loaded. The loading process takes a little bit longer the first time the page is loaded. After that the thumbnail is loaded from cache.

In this article, I will describe the second solution and demonstrate a sleek a way to implement it.

How it Works

The user uploads the image (sample_1.jpg). We can use the image on a page like this: <?php echo img_load('uploads/sample_1.jpg', 'small'); ?>. In this example, "small" is the name of the array that contains all the details of the manipulation, as we will see later.

The benefits of this method are:

  • You do not need to use a particular, predefined format for manipulation
  • You can create any format you want at any time
  • If you want to change a manipulation type you only need to specify the changes in an array and to delete the contents of the cache folder.

We will use for this system a class independent from CodeIgniter called class.upload.php. The class has several benefits and advanced ways to manipulate images. PNG images are handled better by this class than CodeIgniter.

How to Implement It

  • Download the class
  • Upload it to system/application/libraries/class.upload.php
  • Create a new file in system/application/libraries and call it Imaging.php
  • Copy the content below and paste it in that file
<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

// Include the main class
require_once(APPPATH.'libraries/class.upload.php');

// Extend it
class Imaging extends upload {

    function Imaging() { 
        log_message('debug', get_class($this).' Class Initialized');
    }
    
}
// END Imaging Class

/* End of file Imaging.php */
/* Location: ./system/application/libraries/Imaging.php */ 

  • Create or open system/application/helpers/MYhtmlhelper.php and add the following code:
/**
* Image Format
*
* Generates an image file in the specified format, or takes it from cache
* and outputs an <img /> element using Colin Verots upload class. Set different
* formats in /system/application/config/my_image_formats.php
*
*/    
if(!function_exists('img_load')) {
    function img_load($src='', $format='', $index_page=FALSE) {
        // Load a codeigniter instance
        $CI =& get_instance();
        // Get the image format configurations
        $CI->config->load('image_configurations');
        $formats = $CI->config->item('image_config');        
        // The cached name of the file is just a md5 hash of the src and the format
        $hash = md5($format.$src);
        // Get the file extension (if we are converting get the new extension eg. jpg->gif)
        if(isset($formats[$format]['image_convert'])) $ext = '.'.$formats[$format]['image_convert'];
        else $ext = '.'.end(explode('.', $src));
        // Get the general path to the system
        $path = str_replace(SELF,'',FCPATH);    
        // Check if the image has already been generated in the cache
        if(!file_exists($path.'cache/'.$hash.$ext)) {
            // Make sure format is valid
            if(isset($formats[$format])) {
                // Increase memory allowance
                ini_set('memory_limit','36M');  
                // Load the image manipulation library                
                $CI->load->library('imaging');
                $CI->imaging->upload($path.$src);
                if($CI->imaging->uploaded) {
                    // Some default settings
                    $CI->imaging->file_new_name_body = $hash;
                    $CI->imaging->file_auto_rename = FALSE;
                    $CI->imaging->file_overwrite = TRUE;
                    // Settings for the format as defined in the config
                    foreach($formats[$format] as $key => $value) {
                        $CI->imaging->$key = $value;
                    }
                    // Process
                    $CI->imaging->Process($path.'cache');
                    if($CI->imaging->processed) $src = 'cache/'.$hash.$ext;
                }
            }         
        } else $src = 'cache/'.$hash.$ext;
        // Pass to the normal img function
        return img($src, $index_page);
    }
} 

  • Create the file imageconfigurations.php in system/application/config/ and create an array item in _$config for each image manipulation type.
<?php
$config['image_config'][thumb] =  array(                 'image_resize'=>true, 
'image_convert'=>'gif', 
'image_x'=>100, 
'image_y’=>75);
?>
  • Load this file using <?php echo img_format('upload/sample_1.jpg', 'thumb'); ?>. The keys and values must correspond with the image manipulation class settings outlined at in the class documentation.

  • Create the folder at the same level as system called "/cache."

If you have removed the index.php part from the URL don’t forget to update the .htaccess file.

Conclusion

There are a lot of methods to manipulate images in CodeIgniter, including the class built in the framework. The method we have exposed above is very easy to implement and provides a lot of freedom.

Related Articles

0 Comments

Rss-sm