GD library to use the zoom function on the image

Recently on the Internet for some information and then re-packaged into a slightly modified can call the public function
<?php

    define ('IMG_FILTER_CACHE_SIZE', 250);             // number of files to store before clearing cache
    define ('IMG_FILTER_CACHE_CLEAR', 5);              // maximum number of files to delete on each cache clear
    define ('IMG_FILTER_VERSION', '1.09');             // version number (to force a cache refresh

    
    /**
     *  Smaller handler function, when  $width And  $height Is zero, the function defaults to  100x100 Picture  
     *  Use the sample  1:minifyPicture(UPLOAD_PIC_DIR.$main_imagename, 0, 0, 0, 100);
     *  This statement calls the function will target picture equal proportion is converted to a picture of 100x100  , Picture quality is set to  100( That is, the highest quality  )
     *  Use the sample  2:minifyPicture(UPLOAD_PIC_DIR.$main_imagename, 150, 150, 0, 50);
     *  This statement calls the function will target picture equal proportion is converted to a picture of 150x150  , Picture quality is set to  50
     * @param string $src,  The absolute path of a file  
     * @param int $width,  Reduce the width of a picture  
     * @param int $height,  Reduced picture high  
     * @param int $zoom_crop,  Whether the scale, as  0 When scaled, as  1 The only part of the picture  
     * @param int $quality,  Smaller picture quality and value in the  (0,100],100 For the highest quality picture  
     * @return string, Operation successfully, returns an empty string  , Otherwise it returns error information  
     */
    function minifyPicture($src, $width, $height, $zoom_crop, $quality){
        $imageFilters = array(
        "1" => array("IMG_FILTER_NEGATE", 0),
        "2" => array("IMG_FILTER_GRAYSCALE", 0),
        "3" => array("IMG_FILTER_BRIGHTNESS", 1),
        "4" => array("IMG_FILTER_CONTRAST", 1),
        "5" => array("IMG_FILTER_COLORIZE", 4),
        "6" => array("IMG_FILTER_EDGEDETECT", 0),
        "7" => array("IMG_FILTER_EMBOSS", 0),
        "8" => array("IMG_FILTER_GAUSSIAN_BLUR", 0),
        "9" => array("IMG_FILTER_SELECTIVE_BLUR", 0),
        "10" => array("IMG_FILTER_MEAN_REMOVAL", 0),
        "11" => array("IMG_FILTER_SMOOTH", 0),
        );
        
        if($src == "" || strlen($src) <= 3)
            return "no image specified";

//        $orifilesize = filesize($src);
//        if($orifilesize <= 1024*500)
//            return;

        $picinfo = pathinfo($src);
        $picname = $picinfo["basename"];
        // set path to cache directory (default is ./cache)
        // this can be changed to a different location
        $cache_dir = $picinfo['dirname'];
        
        // last modified time (for caching)
        $lastModified = filemtime($src);

//        // get properties
        $new_width              = preg_replace("/[^0-9]+/", "", $width);
        $new_height             = preg_replace("/[^0-9]+/", "", $height);
        $zoom_crop              = preg_replace("/[^0-9]+/", "", $zoom_crop);
        $quality                = preg_replace("/[^0-9]+/", "", $quality);
        $filters                = "";

        if ($new_width == 0 && $new_height == 0) {
            $new_width = 100;
            $new_height = 100;
        }

        

        // get mime type of src
        $mime_type = IMG_FILTER_mime_type($src);

        // check to see if this image is in the cache already
        IMG_FILTER_check_cache( $cache_dir );

        // if not in cache then clear some space and generate a new file
        //cleanCache();

        ini_set('memory_limit', "50M");

        // make sure that the src is gif/jpg/png
        if(!IMG_FILTER_valid_src_mime_type($mime_type)) {
            return "Invalid src mime type: " .$mime_type;
        }

        // check to see if GD function exist
        if(!function_exists('imagecreatetruecolor')) {
            return "GD Library Error: imagecreatetruecolor does not exist";
        }

        if(strlen($src) && file_exists($src)) {

            // open the existing image
            $image = IMG_FILTER_open_image($mime_type, $src);
            if($image === false) {
                return 'Unable to open image : ' . $src;
            }

            // Get original width and height
            $width = imagesx($image);
            $height = imagesy($image);

            // don't allow new width or height to be greater than the original
            if( $new_width > $width ) {
                $new_width = $width;
            }
            if( $new_height > $height ) {
                $new_height = $height;
            }

//            // generate new w/h if not provided
//            if( $new_width && !$new_height ) {
//
//                $new_height = $height * ( $new_width / $width );
//
//            } elseif($new_height && !$new_width) {
//
//                $new_width = $width * ( $new_height / $height );
//
//            } elseif(!$new_width && !$new_height) {
//
//                $new_width = $width;
//                $new_height = $height;
//
//            }

            //assign the start position on the canvas
            if( $height > $width ){
                $dst_height = $new_height;
                $dst_width = $dst_height*($width/$height);
                $dst_x = ( $new_width - $dst_width )/2;
                $dst_y = 0;
            }elseif( $height < $width ){
                $dst_width = $new_width;
                $dst_height = $dst_width*($height/$width);
                $dst_x = 0;
                $dst_y = ( $new_height - $dst_height)/2;
            }elseif( $height == $width ){
                $dst_width = $new_width;
                $dst_height = $new_height;
                $dst_x = 0;
                $dst_y = 0;
            }
            // create a new true color image
            $canvas = imagecreatetruecolor( $new_width, $new_height );
            imagealphablending($canvas, false);
            // Create a new transparent color for image
            $color = imagecolorallocatealpha($canvas, 250, 250, 250, 127);
            // Completely fill the background of the new image with allocated color.
            imagefill($canvas, 0, 0, $color);
            // Restore transparency blending
            imagesavealpha($canvas, true);

            if( $zoom_crop ) {

                $src_x = $src_y = 0;
                $src_w = $width;
                $src_h = $height;

                $cmp_x = $width  / $new_width;
                $cmp_y = $height / $new_height;

                // calculate x or y coordinate and width or height of source

                if ( $cmp_x > $cmp_y ) {

                    $src_w = round( ( $width / $cmp_x * $cmp_y ) );
                    $src_x = round( ( $width - ( $width / $cmp_x * $cmp_y ) ) / 2 );

                } elseif ( $cmp_y > $cmp_x ) {

                    $src_h = round( ( $height / $cmp_y * $cmp_x ) );
                    $src_y = round( ( $height - ( $height / $cmp_y * $cmp_x ) ) / 2 );

                }

                imagecopyresampled( $canvas, $image, 0, 0, $src_x, $src_y, $new_width, $new_height, $src_w, $src_h );

            } else {

                // copy and resize part of an image with resampling
                imagecopyresampled( $canvas, $image, $dst_x, $dst_y, 0, 0, $dst_width, $dst_height, $width, $height );

            }

            if ($filters != "") {
                // apply filters to image
                $filterList = explode("|", $filters);
                foreach($filterList as $fl) {
                    $filterSettings = explode(",", $fl);
                    if(isset($imageFilters[$filterSettings[0]])) {

                        for($i = 0; $i < 4; $i ++) {
                            if(!isset($filterSettings[$i])) {
                                $filterSettings[$i] = null;
                            }
                        }

                        switch($imageFilters[$filterSettings[0]][1]) {

                            case 1:

                                imagefilter($canvas, $imageFilters[$filterSettings[0]][0], $filterSettings[1]);
                                break;

                            case 2:

                                imagefilter($canvas, $imageFilters[$filterSettings[0]][0], $filterSettings[1], $filterSettings[2]);
                                break;

                            case 3:

                                imagefilter($canvas, $imageFilters[$filterSettings[0]][0], $filterSettings[1], $filterSettings[2], $filterSettings[3]);
                                break;

                            default:
                                
                                imagefilter($canvas, $imageFilters[$filterSettings[0]][0]);
                                break;

                            }
                        }
                    }
                }

                // output image to browser based on mime type
                IMG_FILTER_show_image($mime_type, $canvas, $cache_dir, $quality, $picname);

                // remove image from memory
                //imagedestroy($canvas);
                return "";
            } else {

                if(strlen($src)) {
                    return "image " . $src . " not found";
                } else {
                    return "no source specified";
                }

            }

    }  
//=======================================================================================================
/**
 *   The following are some of the secondary processing functions  
 */
        function IMG_FILTER_show_image($mime_type, $image_resized, $cache_dir, $quality, $picname) {

            // check to see if we can write to the cache directory
            $is_writable = 0;
            $cache_file_name = $cache_dir . '/' . $picname;

            if(touch($cache_file_name)) {

                // give 666 permissions so that the developer
                // can overwrite web server user
                chmod($cache_file_name, 0666);
                $is_writable = 1;

            } else {

                $cache_file_name = NULL;
                header('Content-type: ' . $mime_type);

            }

            //$quality = floor($quality * 0.09);

            imagejpeg($image_resized, $cache_file_name, $quality);

            if($is_writable) {
                //IMG_FILTER_show_cache_file($cache_dir, $mime_type, $picname);
            }

            imagedestroy($image_resized);            

        }

/**
 *
 */
        function IMG_FILTER_open_image($mime_type, $src) {

            if(stristr($mime_type, 'gif')) {

                $image = imagecreatefromgif($src);

            } elseif(stristr($mime_type, 'jpeg')) {

                @ini_set('gd.jpeg_ignore_warning', 1);
                $image = imagecreatefromjpeg($src);

            } elseif( stristr($mime_type, 'png')) {

                $image = imagecreatefrompng($src);

            }

            return $image;

        }

/**
 * clean out old files from the cache
 * you can change the number of files to store and to delete per loop in the defines at the top of the code
 */
        function IMG_FILTER_cleanCache() {

            $files = glob("cache/*", GLOB_BRACE);

            $yesterday = time() - (24 * 60 * 60);

            if (count($files) > 0) {

                usort($files, "filemtime_compare");
                $i = 0;

                if (count($files) > IMG_FILTER_CACHE_SIZE) {

                    foreach ($files as $file) {

                        $i ++;

                        if ($i >= IMG_FILTER_CACHE_CLEAR) {
                            return;
                        }

                        if (filemtime($file) > $yesterday) {
                            return;
                        }

                        unlink($file);

                    }

                }

            }

        }

/**
 * compare the file time of two files
 */
        function IMG_FILTER_filemtime_compare($a, $b) {

            return filemtime($a) - filemtime($b);

        }

/**
 * determine the file mime type
 */
        function IMG_FILTER_mime_type($file) {

            if (stristr(PHP_OS, 'WIN')) {
                $os = 'WIN';
            } else {
                $os = PHP_OS;
            }

            $mime_type = '';

            if (function_exists('mime_content_type')) {
                $mime_type = mime_content_type($file);
            }

            // use PECL fileinfo to determine mime type
            if (!IMG_FILTER_valid_src_mime_type($mime_type)) {
                if (function_exists('finfo_open')) {
                    $finfo = finfo_open(FILEINFO_MIME);
                    $mime_type = finfo_file($finfo, $file);
                    finfo_close($finfo);
                }
            }

            // try to determine mime type by using unix file command
            // this should not be executed on windows
            if (!IMG_FILTER_valid_src_mime_type($mime_type) && $os != "WIN") {
                if (preg_match("/FREEBSD|LINUX/", $os)) {
                    $mime_type = trim(@shell_exec('file -bi "' . $file . '"'));
                }
            }

            // use file's extension to determine mime type
            if (!IMG_FILTER_valid_src_mime_type($mime_type)) {

                // set defaults
                $mime_type = 'image/png';
                // file details
                $fileDetails = pathinfo($file);
                $ext = strtolower($fileDetails["extension"]);
                // mime types
                $types = array(
                        'jpg'  => 'image/jpeg',
                        'jpeg' => 'image/jpeg',
                        'png'  => 'image/png',
                        'gif'  => 'image/gif'
                );

                if (strlen($ext) && strlen($types[$ext])) {
                    $mime_type = $types[$ext];
                }

            }

            return $mime_type;

        }

/**
 *
 */
        function IMG_FILTER_valid_src_mime_type($mime_type) {

            if (preg_match("/jpg|jpeg|gif|png/i", $mime_type)) {
                return true;
            }

            return false;

        }

/**
 *
 */
        function IMG_FILTER_check_cache($cache_dir) {

            // make sure cache dir exists
            if (!file_exists($cache_dir)) {
                // give 777 permissions so that developer can overwrite
                // files created by web server user
                mkdir($cache_dir);
                chmod($cache_dir, 0777);
            }
            chmod($cache_dir, 0777);
            //show_cache_file($cache_dir, $mime_type, $lastModified);

        }

/**
 *
 */
        function IMG_FILTER_show_cache_file($cache_dir,$mime_type,$picname) {

            $cache_file = $cache_dir . '/' . $picname;

            if (file_exists($cache_file)) {

                $gmdate_mod = gmdate("D, d M Y H:i:s", filemtime($cache_file));

                if(! strstr($gmdate_mod, "GMT")) {
                    $gmdate_mod .= " GMT";
                }

                if (isset($_SERVER["HTTP_IF_MODIFIED_SINCE"])) {

                    // check for updates
                    $if_modified_since = preg_replace("/;.*$/", "", $_SERVER["HTTP_IF_MODIFIED_SINCE"]);

                    if ($if_modified_since == $gmdate_mod) {
                        header("HTTP/1.1 304 Not Modified");
                        exit;
                    }

                }

                $fileSize = filesize($cache_file);

                // send headers then display image
                header("Content-Type: image/png");
                header("Accept-Ranges: bytes");
                header("Last-Modified: " . $gmdate_mod);
                header("Content-Length: " . $fileSize);
                header("Cache-Control: max-age=9999, must-revalidate");
                header("Expires: " . $gmdate_mod);

                readfile($cache_file);

                exit;

            }

        }

/**
 * check to if the url is valid or not
 */
        function IMG_FILTER_valid_extension ($ext) {

            if (preg_match("/jpg|jpeg|png|gif/i", $ext)) {
                return TRUE;
            } else {
                return FALSE;
            }

        }

?>
  • del.icio.us
  • StumbleUpon
  • Digg
  • TwitThis
  • Mixx
  • Technorati
  • Facebook
  • NewsVine
  • Reddit
  • Google
  • LinkedIn
  • YahooMyWeb

Related Posts of GD library to use the zoom function on the image

  • Hibernate primary key strategy-sequence

    Today, the use of hibernate in the company encountered a troublesome problem, the use of hibernate when the primary key generation strategy set sequence, but always reported in the implementation could not get next sequence value of the error, then o ...

  • hibernate call stored procedure

    hibernate call stored procedure

  • hibernate using c3p0 connection pooling

    Private http://www.lifevv.com/tenyo/doc/20070605102040991.html c3p0 for open source's JDBC connection pool, with the release hibernate. This article describes how to use the hibernate configuration in c3p0. c3p0 connection pool configuration is v ...

  • Hibernate configuration parameters hibernate.hbm2ddl.auto

    Hibernate in the configuration file: <properties> <property name="hibernate.hbm2ddl.auto" value="create" /> </ properties> Parameter Description: validate load hibernate, the authentication to create a database t ...

  • Build flex + spring + blazeds + hibernate application

    Build flex + spring + blazeds + hibernate application First, set up the project blazeds 1, will blazeds.war extract to a directory, such as: myflex /; 2, set up java works were such as: MyFlex, in the orientation of selection create project from exis ...

  • Hibernate connection pool configuration

    Hibernate connection pool configuration <! - Jdbc -> <property name="connection.driver_class"> oracle.jdbc.driver.OracleDriver </ property> <property name="connection.url"> jdbc: oracle: thin: @ 10.203.14.132:15

  • hibernate generic generic DAO

    package org.lzpeng.dao; import java.io.Serializable; import java.util.List; import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.criterion.Criterion; import org.springside.modules.orm.hibernate.Page; /** * * @version 2009-1-10 *

  • Struts2 + hibernate + spring problem user log in

    dao layer services layer action jsp <tr> <td align="center"> <b> user name: </ b> </ td> <td> <s: textfield name = "czyNumber" cssClass = "textstyle" theme = "simple" size = &q

  • Hibernate secondary cache

    Hibernate cache: 2-bit cache, also known as process-level cache or SessionFactory level cache, secondary cache can be shared by all of the session Cache configuration and the use of: Will echcache.xml (the document code in hibernate package directory ...

  • Hibernate's lazy strategy

    hibernate Lazy strategy can be used in: <class> tag, it can be true / false Tags can <PROPERTY> values true / false type of necessary tools to enhance <set> <list> can tag values true / false / extra <many-to-one> <on ...

blog comments powered by Disqus
Recent
Recent Entries
Tag Cloud
Random Entries