php class to manage image upload, resize, crop


Save the class as “image_manage.php” under project root folder or where ever you want.


<?php

class image_manipulation {

    public $relative_path_to_point_img_folder;   //Relative folder path of image going to be uploaded. example "./upload/"
    public $absolute_path_to_point_img_folder;   //Absolute folder path of image going to be uploaded. example "http://www.mysite.com/upload/"
    public $fileFieldName;                       //Image File input field name
    public $allowedMimeTypes = array(
        'jpg|jpeg|jpe' => 'image/jpeg',
        'gif' => 'image/gif',
        'png' => 'image/png',
        'bmp' => 'image/bmp',
        'tif|tiff' => 'image/tiff',
        'ico' => 'image/x-icon'
    );

    /*
     *  constructor takes three arguments
     *  1st: relative path of image folder.  example "./upload/"
     *  2nd: absolute path of image folder.  example "http://www.mysite.com/upload/"
     *  3rd: image file input field name
     */    
    public function __construct($img_folder_relative_path, $img_folder_absolute_path, $img_file_field_name) {
        $this->relative_path_to_point_img_folder = $img_folder_relative_path;
        $this->absolute_path_to_point_img_folder = $img_folder_absolute_path;
        $this->fileFieldName = $img_file_field_name;
    }

    /*
     * validateType function used to check image type and error occured
     * @param
     * $data: $_FILES sould be passed to this variable of the image to be uploaded
     * @return: if ture return image type otherwise false
     */
    public function validateType($data) {
        if (isset($data[$this->fileFieldName]['type']) && $data[$this->fileFieldName]['error'] == 0) {
            return in_array($data[$this->fileFieldName]['type'], $this->allowedMimeTypes);
        }
        return false;
    }

    /*
     * validateUpload function used to check image upload error and size error
     * @param
     * $data: $_FILES sould be passed to this variable of the image to be uploaded
     * @return: true if no error occure otherwise return false
     */
    public function validateUpload($data) {
        if ($data[$this->fileFieldName]['error'] != 0) {
            return $this->uploadError[$data[$this->fileFieldName]['error']];
        }
        if ($data[$this->fileFieldName]['size'] == 0) {
            return false;
        }
        return true;
    }

    /**
     * @param array $fileInfo
     * array index
     * location: relative path to image file
     * width (int): width to resize
     * height (int): height to resize
     * propotional (bool): resize image ratio and original image ration will be same
     * direction (string x): 
     * crop (stirng zoom-in): zoom in crop image would be resized and crop the unmached part
     * quality (int 0~100): quality of the resized image
     * @return: new image url with absolute path
     */
    public function resize($fileInfo) {
        if (!isset($fileInfo['location'])) {
            return false;
        }

        //if not width and height provided return the original file
        if ((!isset($fileInfo['width']) || !$fileInfo['width']) && (!isset($fileInfo['height']) || !$fileInfo['height'])) {
            return $fileInfo['location'];
        }

        //load the image
        $imgInfo = getimagesize($fileInfo['location']);
        $originalWidth = $imgInfo[0];
        $originalHeight = $imgInfo[1];
        $type = $imgInfo[2];
        $propotional = isset($fileInfo['propotional']) ? $fileInfo['propotional'] : false;
        $propotionDirection = isset($fileInfo['direction']) ? $fileInfo['direction'] : 'x';
        $crop = isset($fileInfo['crop']) ? $fileInfo['crop'] : 'zoom-in';
        $quality = isset($fileInfo['quality']) ? $fileInfo['quality'] : 90;
        $srcX = 0;
        $srcY = 0;
        $dstX = 0;
        $dstY = 0;

        //set vars
        $originalRatio = $originalWidth / $originalHeight;
        $resizedWidth = isset($fileInfo['width']) ? $fileInfo['width'] : 0;
        $resizedHeight = isset($fileInfo['height']) ? $fileInfo['height'] : 0;
        if ($resizedWidth == 0) {
            $resizedWidth = round($originalRatio * $resizedHeight);
        }
        if ($resizedHeight == 0) {
            $resizedHeight = round($resizedWidth / $originalRatio);
        }

        if ($propotional) {
            if ($propotionDirection == 'x') {
                $resizedHeight = round($resizedWidth / $originalRatio);
            } else {
                $resizedWidth = round($originalRatio * $resizedHeight);
            }

            $resizedImageName = $resizedWidth . 'X' . $resizedHeight;
        } else {
            $resizedImageName = $resizedWidth . 'X' . $resizedHeight;

            $newRatio = $resizedWidth / $resizedHeight;

            if ($newRatio > $originalRatio) {
                if ($crop == 'zoom-in') {
                    $newWidth = $originalWidth;
                    $newHeight = $newWidth / $newRatio;
                    $resizedImageName .= '_w_zoom_in_';
                } else {
                    $newHeight = $originalHeight;
                    $newWidth = $newRatio * $newHeight;
                    $dstX = ($resizedWidth - $resizedHeight * $originalRatio) / 2;

                    $resizedImageName .= '_w_zoom_out_';
                }
            } else {
                if ($crop == 'zoom-in') {
                    $newHeight = $originalHeight;
                    $newWidth = $newRatio * $newHeight;
                    $srcX = $originalWidth / 2 - $newWidth / 2;

                    $resizedImageName .= '_h_zoom_in_';
                } else {
                    $newWidth = $originalWidth;
                    $newHeight = $newWidth / $newRatio;
                    $dstY = ($resizedHeight - ($resizedWidth / $originalRatio)) / 2;

                    $resizedImageName .= '_w_zoom_out_';
                }
            }

            $originalHeight = $newHeight;
            $originalWidth = $newWidth;
        }


        $resizedImageName .= $quality . '_' . str_replace(' ', '_', strtolower($fileInfo['file_name']));
        $destination = $this->relative_path_to_point_img_folder . $resizedImageName;
        $image_return_url = $this->absolute_path_to_point_img_folder . $resizedImageName;

        //check if file already exits
        if (file_exists($destination)) {
            return $destination;
        }

        $canvas = imagecreatetruecolor($resizedWidth, $resizedHeight);

        //transparency staff
        if ($type == IMAGETYPE_GIF || $type == IMAGETYPE_PNG) {
            //not working need to fix
            //imagefill($canvas, 0, 0, IMG_COLOR_TRANSPARENT);
            //imagesavealpha($canvas, true);
            //imagealphablending($canvas, true);
        }

        switch ($type) {
            case IMAGETYPE_GIF:
                $image = imagecreatefromgif($fileInfo['location']);
                break;
            case IMAGETYPE_JPEG:
                $image = imagecreatefromjpeg($fileInfo['location']);
                break;
            case IMAGETYPE_PNG:
                $image = imagecreatefrompng($fileInfo['location']);
                break;
            default:
                return false;
        }
        imagecopyresampled($canvas, $image, $dstX, $dstY, $srcX, $srcY, $resizedWidth, $resizedHeight, $originalWidth, $originalHeight);


        switch ($type) {
            case IMAGETYPE_GIF:
                imagegif($canvas, $destination);
                break;
            case IMAGETYPE_JPEG:
                imagejpeg($canvas, $destination, $quality);
                break;
            case IMAGETYPE_PNG:
                $quality = 9 - (int) ((0.9 * $quality) / 10.0);
                imagepng($canvas, $destination, $quality);
                break;
            default:
                return false;
        }

        //return $destination;
        return $image_return_url;
    }

    /**
     * @param 
     * $filename: only image file name going to be croped
     * x1 (int): x1 coordinate value
     * y1 (int): y1 coordinate value
     * x4 (int): x4 coordinate value
     * y4 (int): y4 coordinate value
     * @return: new image url with absolute path
     */
    public function crop($filename, $x1, $y1, $x4, $y4) {
        
        $filename_location = $this->relative_path_to_point_img_folder . $filename;
        
        if (!file_exists($filename_location)) {
            return false;
        }
                
        $imgInfo = getimagesize($filename_location);
        $originalWidth = $imgInfo[0];
        $originalHeight = $imgInfo[1];
        $type = $imgInfo[2];
        $new_width = ( $x4 - $x1 );
        $new_height = ( $y4 - $y1 );
        
        $cropedImageName = $x1.$y1."_".$new_width."X".$new_height."_".$filename;
        $destination = $this->relative_path_to_point_img_folder . $cropedImageName;
        $image_return_url = $this->absolute_path_to_point_img_folder . $cropedImageName;

        //check if file already exits
        if (file_exists($destination)) {
            return $image_return_url;
        }

        $canvas = imagecreatetruecolor($new_width, $new_height);
        
        switch ($type) {
            case IMAGETYPE_GIF:
                $image = imagecreatefromgif($filename_location);
                break;
            case IMAGETYPE_JPEG:
                $image = imagecreatefromjpeg($filename_location);
                break;
            case IMAGETYPE_PNG:
                $image = imagecreatefrompng($filename_location);
                break;
            default:
                return false;
        }        
        
        imagecopyresampled($canvas, $image, 0, 0, $x1, $y1, $new_width, $new_height, $new_width, $new_height);
        
        switch ($type) {
            case IMAGETYPE_GIF:
                imagegif($canvas, $destination);
                break;
            case IMAGETYPE_JPEG:
                $quality = 95;
                imagejpeg($canvas, $destination, $quality);
                break;
            case IMAGETYPE_PNG:
                $quality = 9 - (int) ((0.9 * $quality) / 10.0);
                imagepng($canvas, $destination, $quality);
                break;
            default:
                return false;
        }
        
        return $image_return_url;
    }

    /**
     * @param 
     * $data: $_FILES sould be passed to this variable of the image to be uploaded
     * @return: if uploaded successfully its return an array with values otherwise it return empty array
     */
    public function upload($data) {
        $original_file_name = $data[$this->fileFieldName]['name'];
        $new_file_name = time() . $original_file_name;
        $image_actual_file_location = $this->relative_path_to_point_img_folder . $new_file_name;
        $image_return_url = $this->absolute_path_to_point_img_folder . $new_file_name;
        $file_temp_name = $data[$this->fileFieldName]['tmp_name'];
        $arr = array();
        if ($this->validateType($data)) {
            if (move_uploaded_file($file_temp_name, $image_actual_file_location)) {
                $arr = array(
                    'original_file_name' => $original_file_name,
                    'new_file_name' => $new_file_name,
                    'image_relative_url' => $image_actual_file_location,
                    'image_absolute_url' => $image_return_url
                );
                return $arr;
            } else {
                return $arr;
            }
        } else {
            return $arr;
        }
    }

    /**
     * @param 
     * $img_name: Image name going to be removed completely.
     * @return: if removed it will return true otherwise false.
     */
    public function remove($img_name){        
        $destination = $this->relative_path_to_point_img_folder . $img_name;        
        if (!file_exists($destination)) {
            $this->error = 'File not found';
            return false;
        }        
        $res = unlink($destination);
        return $res;        
    }

}

?>

To make it workable at view please check the below how i am calling:


<?php
//include the image_manage.php class by defining its actual location
include './image_manage.php';  

//create an object of image_manipulation class
$image = new image_manipulation('./upload/', 'http://www.mysite.com/upload/', 'fileToUpload');
$url = $image->crop('mytest_image.jpg', 100, 50, 700, 400);

?>


Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s