`
liboxlu
  • 浏览: 63313 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

使用GD库对图片的缩放功能函数

阅读更多
最近在网上找了些资料,然后稍微修改重新封装成了一个可以直接调用的公共函数
<?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

    
    /**
     * 缩小图片的处理函数,当$width和$height都为零时,函数默认为100x100的图片
     * 使用示例1:minifyPicture(UPLOAD_PIC_DIR.$main_imagename, 0, 0, 0, 100);
     * 这个语句会调用函数将目标图片等比例转换为100x100的图片,图片质量设为100(即最高质量)
     * 使用示例2:minifyPicture(UPLOAD_PIC_DIR.$main_imagename, 150, 150, 0, 50);
     * 这个语句会调用函数将目标图片等比例转换为150x150的图片,图片质量设为50
     * @param string $src, 文件的绝对路径
     * @param int $width, 缩小后的图片宽
     * @param int $height, 缩小后的图片高
     * @param int $zoom_crop, 是否等比例缩放,为0时按等比例缩小,为1则只取图片一部分
     * @param int $quality, 缩小图片的画面质量,取值在(0,100],100为画面最高质量
     * @return string,操作成功,返回空字符串,否则返回错误提示信息
     */
    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";
                }

            }

    }  
//=======================================================================================================
/**
 *  以下是一些辅助处理函数
 */
        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;
            }

        }

?>
0
0
分享到:
评论

相关推荐

    php gd等比例缩放压缩图片函数_.docx

    php gd等比例缩放压缩图片函数_.docx

    php gd等比例缩放压缩图片函数

    主要为大家详细介绍了php gd等比例缩放压缩图片函数,文章末尾为大家分享了php and gd 函数参考表,感兴趣的小伙伴们可以参考一下

    PHP基于GD库实现的生成图片缩略图函数示例

    本文实例讲述了PHP基于GD库实现的生成图片缩略图函数。分享给大家供大家参考,具体如下: &lt;?php /** * 生成缩略图函数(支持图片格式:gif、jpeg、png和bmp) * @author ruxing.li * @param string $src 源...

    解析php中两种缩放图片的函数,为图片添加水印

    有两种改变图像大小的方法.(1):ImageCopyResized() 函数在所有GD版本中有效,但其缩放图像的算法比较粗糙.(2):ImageCopyResampled(),其像素插值算法得到的图像边缘比较平滑.质量较好(但该函数的速度比 ...

    使用PHP生成缩略图教程示例

    PHP生成缩略图 一、开发环境 1、环境搭建:Windows 8+Apache 2.4.18+MySQL 5.7.11+PHP 7.1.0 。 2、文本编辑器:Sublime Text3。 二、主要技术 本实验主要使用PHP GD库的图片缩放、裁剪等函数完成。

    GD5F1GQ4UAYIG.PDF

    GD5F1GQ4UAYIG SPI NAND FLASH 文档描述详细coder: 通过 CreateVideoDecoder 函数创建的视频解码器指针; nScaleDownRatio: 图像缩放比例因子。 返回值 0: 表示成功;-1: 失败

    PHP图片处理之图片背景、画布操作

    在web应用中,经常使用的图片格式有GIF、JPEG和PNG中的一种或几种,当然GD库也可以处理其他格式的图片,但都很少用到。所以安装GD库时,至少安装GIF、JPEG或PNG三种格式中的一种。  在前面介绍的画布管理中,使用...

    php生成三种缩略图的函数类

    一个php生成三种缩略图的函数类,把大图缩略到...把大图缩略到缩略图指定的范围内,不留白(原图会居中缩放,把超出的部分裁剪掉);把大图缩略到缩略图指定的范围内,不留白(原图会剪切掉不符合比例的右边和下边)。

    PHP制作3D扇形统计图以及对图片进行缩放操作实例

    1、利用php gd库的函数绘制3D扇形统计图 &lt;?phpheader(content-type,text/html;charset=utf-8);/*扇形统计图*/$image = imagecreatetruecolor(100, 100); /*创建画布*//*设置画布需要的颜色*/$white = ...

    PHP自动生成缩略图函数的源码示例

    一个简单但功能比较完善的自动生成缩略图的函数,可以按需要对图片进行缩放、裁切、锁定宽或高、使用空白填充 以下为源码,比较简单,相信很容易看明白,记得打开 GD 库的支持哦: &lt;?php /** * 生成缩略图 * @...

    PHP实现绘制3D扇形统计图及图片缩放实例

    1、利用php gd库的函数绘制3D扇形统计图 &lt;?php header(content-type,text/html;charset=utf-8); /*扇形统计图*/ $image = imagecreatetruecolor(100, 100); /*创建画布*/ /*设置画布需要的颜色*/ $white =...

    php下用GD生成生成缩略图的两个选择和区别

    ImageCopyResized( )函数在所有GD版本中有效,但其缩放图像的算法比较粗糙,可能会导致图像边缘的锯齿。GD 2.x中新增了一个ImageCopyResampled( )函数,其像素插值算法得到的图像边缘比较平滑(但该函数的速度比...

    WordPress博客主题 Beginning(更新至 4.1.1 版本)

    采用 WordPress 自带函数进行裁剪(默认支持 GD 和 Imagick 两个库,有一个即可正常裁剪) 支持广告位,可以选择在线上传广告图片或者自定义广告代码;在开启响应式布局的情况下可以自定义广告在哪些平台上显示(PC ...

    牛叉内容管理系统(NiuXcms) v1.07.rar

    5. 原上传图片最大允许的边长900像素,超过会自动等比缩放,修改为不缩放。 6. 编辑器 撤销 次数增加到200次。 7. 编辑器 自动排版 可自动保存个人偏好。 8. 添加/修改文章界面增加“关键词搜索相关文章列表”插入...

    生成缩略图的PHP类.zip

     echo "你的GD库不能使用GIF格式的图片,请使用Jpeg或PNG格式!返回";  exit();  }生成缩略图函数(支持图片格式:gif、jpeg、png和bmp) * @author ruxing.li * @param string $src 源图片路径 * @...

    jblog1.5开源博客程序

    2、支持上传图片添加水印,图片自动缩放,生成缩略图等。 JBLOGv1.5更新列表----------------------------------- 功能修改: 1、增加文章自动摘要功能和没有摘要时全文输出开关。 2、增加文章别名是否重复判断。 3...

Global site tag (gtag.js) - Google Analytics