PHP 图片处理

缩小图片

// 如果尺寸过大 >300kb,则减小尺寸
if($attach['size'] > 300000) {
$create_fun_map = array('jpg' => 'imagecreatefromjpeg', 'jpeg' => 'imagecreatefromjpeg', 'gif' => 'imagecreatefromgif', 'png' => 'imagecreatefrompng');
if ($create_fun_map[$attach['extension']]) {
$create_fun = $create_fun_map[$attach['extension']];
$src_img = $create_fun($attach['target']);
imagejpeg($src_img, $attach['target'], 70);
imagedestroy($src_img);
}
}

图片处理扩展类:

class image_ext {
    /*
     * 图片微缩白边补齐
     * 所用的是GD库
     *  $suffix 新图片后缀名称,如果为空,则为width_height; 缩略图后缀为:   ‘thumb’
     *  图片统一后缀 .jpg
     */

    function PicZoom($pic_path, $width = 200, $height = 200, $suffix = '', $bk_rgb = array(255, 255, 255), $is_del_ori=false) {

        if (!$pic_path || !file_exists($pic_path)) {
            return false;
        }

        if (!function_exists('imagecreatetruecolor')) {
            return false;
        }

        $arr_src = array();
        $arr_tmp = getimagesize($pic_path);
        if (!$arr_tmp) {
            return false; //不是图片    
        }

        //获得原始图像的大小
        $arr_src ['width'] = $arr_tmp [0];
        $arr_src ['height'] = $arr_tmp [1];
        //取得文件扩展名
        $mime_tmp = explode('/', $arr_tmp['mime']);
        $ext = $mime_tmp[1];

        //生成的新图片后缀,一律存成JPG
        if ($suffix) {
            if (strpos($suffix, '/') !== false) {
                return false;
            }
            $suffix = trim($suffix, '.');
        }
        $suffix = $suffix ? $suffix : $width . '_' . $height;
        $arr_src ['new_path'] = $pic_path . '.' . $suffix . '.jpg';

        //如果新生成图片的尺寸宽与高都大于原图,则不压缩补白
        if ($width > $arr_src ['width'] && $height > $arr_src ['height']) {
            return $this->savePic($pic_path, $suffix);
        }
        //根据比例计算新的长宽 目标的坐标x y
        if ($width / $height > $arr_src ['width'] / $arr_src ['height']) { //以height为基准
            $arr_src ['new_height'] = $height;
            $arr_src ['new_width'] = $arr_src ['width'] / $arr_src ['height'] * $height;
            $arr_src ['to_x'] = ($width - $arr_src ['new_width']) / 2;
            $arr_src ['to_y'] = 0;
        } else { //以width为基准
            $arr_src ['new_width'] = $width;
            $arr_src ['new_height'] = $arr_src ['height'] / $arr_src ['width'] * $width;
            $arr_src ['to_x'] = 0;
            $arr_src ['to_y'] = ($height - $arr_src ['new_height']) / 2;
        }
        //列出创建图片资源的函数表
        $create_fun_map = array('jpg' => 'imagecreatefromjpeg', 'jpeg' => 'imagecreatefromjpeg', 'gif' => 'imagecreatefromgif', 'png' => 'imagecreatefrompng');
        if (!$create_fun_map [$ext])
            return false;
        $create_fun = $create_fun_map [$ext];

        //参数计算完毕,创建图像
        $dst_img = imagecreatetruecolor($width, $height);
        $bk_color = imagecolorallocate($dst_img, 0xFF, 0xFF, 0xFF);
        imagefill($dst_img, 0, 0, $bk_color);

        $src_img = $create_fun($pic_path);
        imagecopyresampled($dst_img, $src_img, $arr_src ['to_x'], $arr_src ['to_y'], 0, 0, $arr_src ['new_width'], $arr_src ['new_height'], $arr_src ['width'], $arr_src ['height']);
        //输出到文件
        //$arr_src ['new_path'] = $oldimgurlArr[0].'/'.$oldimgurlArr[1].'/'.$oldimgurlArr[2].'/'.$oldimgurlArr[3].'/'.date('Ym').'/'.date('d').'/'.$oldimgurlArr[6] . $width . '_' . $height . '.jpg';
        $targetpath = dirname($arr_src ['new_path']);
        dmkdir($targetpath);
        //如果没有此文件夹就创建文件夹
        imagejpeg($dst_img, $arr_src ['new_path']);

        //销毁各方资源
        imagedestroy($dst_img);
        imagedestroy($src_img);
        if ($is_del_ori) {
            @unlink($pic_path);
        }
        return true;
    }

    /*
     *  图片另存为 指定后缀的文件
     *  原旨在保存原图
     */

    function savePic($pic_path, $suffix = 'original') {
        if (!$suffix || strpos($suffix, '/') !== false) {
            return false;
        }
        $suffix = trim($suffix, '.');
        $new_path = $pic_path . '.' . $suffix . '.jpg';
        
        if (@copy($source, $new_path)) {
            return true;
        } elseif (@is_readable($source) && (@$fp_s = fopen($source, 'rb')) && (@$fp_t = fopen($new_path, 'wb'))) {
            while (!feof($fp_s)) {
                $s = @fread($fp_s, 1024 * 512);
                @fwrite($fp_t, $s);
            }
            fclose($fp_s);
            fclose($fp_t);
            return true;
        } else {
            $content = file_get_contents($pic_path);
            file_put_contents($new_path, $content);
            return true;
        }         
    }

    /*
     * 上传指定大小的图片
     */

    function uploadedPicZoom($filesArr, $w, $h, $pic_path) {

        if ((($filesArr ["file"] ["type"] == "image/gif")
                || ($filesArr ["file"] ["type"] == "image/jpeg")
                || ($filesArr ["file"] ["type"] == "image/pjpeg"))
                && ($filesArr ["file"] ["size"] < 204800)) {
            if ($filesArr ["file"] ["error"] > 0) {
                print '文件类型错误';
                return false;
            } else {
                $file_name = time() . $filesArr ["file"] ["name"];

                if (file_exists($pic_path . $file_name)) {
                    print '文件重名';
                    return false;
                } else {
                    $targetpath = dirname($pic_path . $file_name);
                    dmkdir($targetpath);
                    move_uploaded_file($filesArr ["file"] ["tmp_name"], $pic_path . $file_name);
                    return $this->PicZoom($pic_path . $file_name, $w, $h, $w . '_' . $h, $bk_rgb = array(255, 255, 255), true);
                }
            }
        } else {
            print '格式错误或者文件太大';
            return false;
        }
    }

    /**
     *  上传图片压缩截取 生成指定宽高的图片
     *  $suffix 新图片后缀名称,如果为空,则为width_height; 缩略图后缀为:   ‘thumb’
     *  图片统一后缀 .jpg
     *  
     */
    function PicCompress($pic_path, $width = 100, $height = 100, $suffix = '') {

        if (!$pic_path || !file_exists($pic_path)) {
            return false;
        }

        if (!function_exists('imagecreatetruecolor')) {
            return false;
        }
        $arr_tmp = getimagesize($pic_path);

        if (!$arr_tmp) {
            return false; //不是图片    
        }

        $arr_src = array();
        //获得原始图像的大小
        $arr_src ['width'] = $arr_tmp [0];
        $arr_src ['height'] = $arr_tmp [1];
        //取得文件扩展名
        $mime_tmp = explode('/', $arr_tmp['mime']);
        $ext = $mime_tmp[1];

        //生成的新图片后缀,一律存成JPG
        if ($suffix) {
            if (strpos($suffix, '/') !== false) {
                return false;
            }
            $suffix = trim($suffix, '.');
        }
        $suffix = $suffix ? $suffix : $width . '_' . $height;
        $arr_src ['new_path'] = $pic_path . '.' . $suffix . '.jpg';

        //如果新生成图片的尺寸宽与高都大于原图,则不压缩截取
        if ($width > $arr_src ['width'] && $height > $arr_src ['height']) {
            return $this->savePic($pic_path, $suffix);
        }
        //如果新生成图片的尺寸宽或高大于原图,则按宽或高缩放原图
        if ($width > $arr_src ['width'] || $height > $arr_src ['height']) {
            //$this->PicZoom($pic_path, $width, $height);
            return $this->PicSourceZoom($pic_path, $width, $height, $suffix);
        }

        //根据比例计算新的长宽 目标的坐标x y
        if ($width / $height > $arr_src ['width'] / $arr_src ['height']) { //以width为基准
            $arr_src ['new_height'] = $width * ($arr_src ['height'] / $arr_src ['width']);
            $arr_src ['new_width'] = $width;
            $arr_src ['src_y'] = ($arr_src ['new_height'] - $height) / 2;
            $arr_src ['src_x'] = 0;
        } else { //以height为基准
            $arr_src ['new_height'] = $height;
            $arr_src ['new_width'] = $height * ($arr_src ['width'] / $arr_src ['height']);
            $arr_src ['src_x'] = ($arr_src ['new_width'] - $width) / 2;
            $arr_src ['src_y'] = 0;
        }

        //列出创建图片资源的函数表
        $create_fun_map = array('jpg' => 'imagecreatefromjpeg', 'jpeg' => 'imagecreatefromjpeg', 'gif' => 'imagecreatefromgif', 'png' => 'imagecreatefrompng');
        if (!$create_fun_map [$ext])
            return false;
        $create_fun = $create_fun_map [$ext];

        //参数计算完毕,创建图像
        $dst_img = imagecreatetruecolor($width, $height);
        $bk_color = imagecolorallocate($dst_img, 255, 255, 255);
        imagefill($dst_img, 0, 0, $bk_color);

        $src_img = $create_fun($pic_path);
        imagecopyresampled($dst_img, $src_img, 0, 0, $arr_src ['src_x'], $arr_src ['src_y'], $arr_src ['new_width'], $arr_src ['new_height'], $arr_src ['width'], $arr_src ['height']);
        //输出到文件
        $targetpath = dirname($arr_src ['new_path']);
        dmkdir($targetpath);
        //如果没有此文件夹就创建文件夹
        imagejpeg($dst_img, $arr_src ['new_path'], 95);

        //销毁各方资源
        imagedestroy($dst_img);
        imagedestroy($src_img);
        return true;
    }

    /**
     * 上传图片压缩截取 生成指定宽高的图片
     * 所用的是GD库
     */
    function PicCompressNewPath($pic_path, $width = 100, $height = 100, $newpath = '', $suffix = '') {

        if (!$pic_path || !file_exists($pic_path)) {
            return false;
        }

        if (!function_exists('imagecreatetruecolor')) {
            return false;
        }
        if (empty($newpath))
            $newpath = $pic_path;
        $arr_src = array();
        $arr_tmp = getimagesize($pic_path);
        if (!$arr_tmp) {
            return false; //不是图片    
        }

        //获得原始图像的大小
        $arr_src ['width'] = $arr_tmp [0];
        $arr_src ['height'] = $arr_tmp [1];
        //取得文件扩展名
        $mime_tmp = explode('/', $arr_tmp['mime']);
        $ext = $mime_tmp[1];
        //生成的新图片后缀,一律存成JPG
        if ($suffix) {
            if (strpos($suffix, '/') !== false) {
                return false;
            }
            $suffix = trim($suffix, '.');
        }
        $suffix = $suffix ? $suffix : $width . '_' . $height;
        $arr_src ['new_path'] = $newpath . '.' . $suffix . '.jpg';

        //根据比例计算新的长宽 目标的坐标x y
        if ($width / $height > $arr_src ['width'] / $arr_src ['height']) { //以width为基准
            $arr_src ['new_height'] = $width * ($arr_src ['height'] / $arr_src ['width']);
            $arr_src ['new_width'] = $width;
            $arr_src ['src_y'] = ($arr_src ['new_height'] - $height) / 2;
            $arr_src ['src_x'] = 0;
        } else { //以height为基准
            $arr_src ['new_height'] = $height;
            $arr_src ['new_width'] = $height * ($arr_src ['width'] / $arr_src ['height']);
            $arr_src ['src_x'] = ($arr_src ['new_width'] - $width) / 2;
            $arr_src ['src_y'] = 0;
        }

        //列出创建图片资源的函数表
        $create_fun_map = array('jpg' => 'imagecreatefromjpeg', 'jpeg' => 'imagecreatefromjpeg', 'gif' => 'imagecreatefromgif', 'png' => 'imagecreatefrompng');
        if (!$create_fun_map [$ext])
            return false;
        $create_fun = $create_fun_map [$ext];

        //参数计算完毕,创建图像
        $dst_img = imagecreatetruecolor($width, $height);
        $bk_color = imagecolorallocate($dst_img, 255, 255, 255);
        imagefill($dst_img, 0, 0, $bk_color);

        $src_img = $create_fun($pic_path);
        imagecopyresampled($dst_img, $src_img, 0, 0, $arr_src ['src_x'], $arr_src ['src_y'], $arr_src ['new_width'], $arr_src ['new_height'], $arr_src ['width'], $arr_src ['height']);
        //输出到文件
        $targetpath = dirname($arr_src ['new_path']);
        dmkdir($targetpath);
        //如果没有此文件夹就创建文件夹
        imagejpeg($dst_img, $arr_src ['new_path'], 95);

        //销毁各方资源
        imagedestroy($dst_img);
        imagedestroy($src_img);
        return true;
    }

    /**
     * 图片按指定的宽,或高缩放,重新生成
     * 如果没有后缀,则直接缩放原图
     * @param $pic_path
     * @param $width 指定图片宽
     * @param $height 指定图片高
     */
    function PicSourceZoom($pic_path, $width = '', $height = '', $suffix = '') {
        if (!$pic_path || !file_exists($pic_path)) {
           return false;
        }
        if (!$width && !$height) {
           return false;
        }        
        if (!function_exists('imagecreatetruecolor')) {
           return false;
        }
        $arr_src = array();
        $arr_tmp = getimagesize($pic_path);
        if (!$arr_tmp) {
           return false; //不是图片    
        }

        //获得原始图像的大小
        $arr_src ['width'] = $arr_tmp [0];
        $arr_src ['height'] = $arr_tmp [1];
        
        //如果新生成图片的尺寸宽与高都大于原图,则不压缩图片,另存指定尺寸图片
        if ($width > $arr_src ['width'] && $height > $arr_src ['height'] && $suffix) {
            return $this->savePic($pic_path, $suffix);
        }
        //如果新生成图片的尺寸宽大于原图,宽需重新指定
        if ($width > $arr_src ['width']) {
            $width = '';
        }
        if ($height > $arr_src ['height']) {
            $height = '';
        }
        if (!$width && !$height) {
           return false;
        }
        //重新定义给定的等比压缩宽,高
        if ($width && $width > $arr_src ['width']) {
            $width = $arr_src ['width'];
        }
        if ($height && $height > $arr_src ['height']) {
            $height = $arr_src ['height'];
        }
        //取得文件扩展名
        $mime_tmp = explode('/', $arr_tmp['mime']);
        $ext = $mime_tmp[1];
        if ($suffix) {
            if (strpos($suffix, '/') !== false) {
                return false;
            }
            $suffix = trim($suffix, '.');
            $arr_src ['new_path'] = $pic_path . '.' . $suffix . '.jpg';
        } else {
            $arr_src ['new_path'] = $pic_path;
        }
        //根据给定宽、高计算目标坐标x y
        if ($width && !$height) {
            $arr_src ['new_width'] = $width;
            $arr_src ['new_height'] = $arr_src ['height'] / $arr_src ['width'] * $width;
            $height = $arr_src ['height'] / $arr_src ['width'] * $width;
        }
        if (!$width && $height) {
            $arr_src ['new_height'] = $height;
            $arr_src ['new_width'] = $arr_src ['width'] / $arr_src ['height'] * $height;
            $width = $arr_src ['width'] / $arr_src ['height'] * $height;
        }
        $arr_src ['to_x'] = 0;
        $arr_src ['to_y'] = 0;
        //列出创建图片资源的函数表
        $create_fun_map = array('jpg' => 'imagecreatefromjpeg', 'jpeg' => 'imagecreatefromjpeg', 'gif' => 'imagecreatefromgif', 'png' => 'imagecreatefrompng');
        if (!$create_fun_map [$ext])
           return false;
        $create_fun = $create_fun_map [$ext];
        //参数计算完毕,创建图像
        $dst_img = imagecreatetruecolor($width, $height);
        $bk_color = imagecolorallocate($dst_img, 0xFF, 0xFF, 0xFF);
        imagefill($dst_img, 0, 0, $bk_color);

        $src_img = $create_fun($pic_path);
        imagecopyresampled($dst_img, $src_img, $arr_src ['to_x'], $arr_src ['to_y'], 0, 0, $arr_src ['new_width'], $arr_src ['new_height'], $arr_src ['width'], $arr_src ['height']);
        //输出到文件
        $targetpath = dirname($arr_src ['new_path']);
        dmkdir($targetpath);
        //如果没有此文件夹就创建文件夹
        imagejpeg($dst_img, $arr_src ['new_path'], 100);

        //销毁各方资源
        imagedestroy($dst_img);
        imagedestroy($src_img);
        return true;
    }

    /*
     *  原图生成不同尺寸的图片,
     *  压缩截取
     */

    function manySizesPicCompress($pic_path, $sizesArr, $bk_rgb = array(255, 255, 255)) {
        if (!is_array($sizesArr) || count($sizesArr) == 0) {
            echo 'sizesArr  error';
        }
        foreach ($sizesArr as $value) {
            $width = $value['width'];
            $height = $value['height'];
            if (!$width || !$height) {
                continue;
            }
            $zoomtype = $value['zoomtype'];
            if ($zoomtype) {
                $this->PicCompress($pic_path, $width, $height);
            } else {
                $this->PicZoom($pic_path, $width, $height);
            }
        }
    }

}
原文地址:https://www.cnblogs.com/bandbandme/p/3905040.html