php图片上传类(支持缩放、裁剪、图片缩略功能)

  • 代码:
    /**
    * @author [Lee] <[<[email protected]>]>
    * 1、自动验证文件是表单提交的文件还是base64流提交的文件
    * 2、验证图片类型是否合法
    * 3、验证图片尺寸是否合法
    * 4、验证图片大小是否合法
    * 5、支持缩放功能
    * 6、支持裁剪功能
    * 7、支持缩略图功能
    */
    class fileuploader{
    private $file;
    private $type;
    public $suffix = array();
    public $measure = array();
    public $size = array();
    public $scale = array(
            ‘is_scale‘=>0,
            ‘ratio‘=>1
        );
    public $crop = array(
            ‘is_crop‘=>0,
            ‘width‘=>0,
            ‘height‘=>0
        );
    public $thumb = array(
            ‘is_thumb‘=>0,
            ‘width‘=>0,
            ‘height‘=>0
        );
    public function __construct($file){
        $this->file = $file;
        $this->getType();
    }
    /*
     内部方法:获取图片类型
     1、多文件
     2、单文件
     3、base64流文件
     */
    private function getType(){
        $file = $this->file;
        if(is_array($file)){
            // 多文件
            if(is_array($file[‘name‘])){
                $type = 1;
            }else{  // 单文件
                $type = 2;
            }
        }else{
            $type = 3;
        }
        $this->type = $type;
    }
    /*
     内部方法:获取图片后缀
     @param path 图片路径
     @return suffix 后缀名 如:jpg
     */
    private function getSuffix($path) {
        $file = fopen($path, "rb");
        $bin = fread($file, 2); // 只读2字节
        fclose($file);
        $strInfo = @unpack("C2chars", $bin);
        $typeCode = intval($strInfo[‘chars1‘] . $strInfo[‘chars2‘]);
        $suffix = "unknow";
        if($typeCode == 255216){
            $suffix = "jpg";
        }elseif($typeCode == 7173){
            $suffix = "gif";
        }elseif($typeCode == 13780){
            $suffix = "png";
        }elseif($typeCode == 6677){
            $suffix = "bmp";
        }elseif($typeCode == 7798){
            $suffix = "exe";
        }elseif($typeCode == 7784){
            $suffix = "midi";
        }elseif($typeCode == 8297){
            $suffix = "rar";
        }elseif($typeCode == 7368){
            $suffix = "mp3";
        }elseif($typeCode == 0){
            $suffix = "mp4";
        }elseif($typeCode == 8273){
            $suffix = "wav";
        }
        return $suffix;
    }
    /*
     内部方法:保存流文件
     @param stream 文件流
     @param suffix 后缀
     @param dir 保存文件夹
     @return path 文件路径
     */
    private function uploadBase64($stream,$suffix,$dir) {
        if (empty($stream)) return false;
        if (preg_match(‘/^(data:(\s)?(image|img)\/(\w+);base64,)/‘, $stream, $str)) {
            $path = $dir . md5(rand(100000, 999999)) . ".{$suffix}";
            if (file_put_contents($path, base64_decode(str_replace($str[1], ‘‘, $stream)))) {
                return $path;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }
    /*
     校验文件类型是否合法
     @return ret true:合法 false:非法
     */
    public function checkType(){
        $file = $this->file;
        $type = $this->type;
        $validSuffix = $this->suffix;
        $ret = true;
        if($type==1){   // 多文件
            foreach($file[‘tmp_name‘] as $v){
                $suffix = $this->getSuffix($v);
                if(!in_array($suffix,$validSuffix)){
                    $ret = false;
                    break;
                }
            }
        }elseif($type==2){  // 单文件
            $suffix = $this->getSuffix($file[‘tmp_name‘]);
            if(!in_array($suffix,$validSuffix)){
                $ret = false;
            }
        }else{  // base64文件
            $suffix = $this->getSuffix($file);
            if(!in_array($suffix,$validSuffix)){
                $ret = false;
            }
        }
        return $ret;
    }
    /*
     校验文件尺寸是否合法
     @return ret true:合法 false:非法
     */
    public function checkMeasure(){
        $file = $this->file;
        $type = $this->type;
        $validMeasure = $this->measure;
        $ret = true;
        if($type==1){   // 多文件
            foreach($file[‘tmp_name‘] as $v){
                $measure = getimagesize($v);
                $width = $measure[0];
                $height = $measure[1];
                if(($width < $validMeasure[‘width‘][0] || $width > $validMeasure[‘width‘][1]) || ($height < $validMeasure[‘height‘][0] || $height > $validMeasure[‘height‘][1])){
                    $ret = false;
                    break;
                }
            }
        }elseif($type==2){  // 单文件
            $measure = getimagesize($file[‘tmp_name‘]);
            $width = $measure[0];
            $height = $measure[1];
            if(($width < $validMeasure[‘width‘][0] || $width > $validMeasure[‘width‘][1]) || ($height < $validMeasure[‘height‘][0] || $height > $validMeasure[‘height‘][1])){
                $ret = false;
            }
        }else{  // base64文件
            $measure = getimagesize($file);
            $width = $measure[0];
            $height = $measure[1];
            if(($width < $validMeasure[‘width‘][0] || $width > $validMeasure[‘width‘][1]) || ($height < $validMeasure[‘height‘][0] || $height > $validMeasure[‘height‘][1])){
                $ret = false;
            }
        }
        return $ret;
    }
    /*
     校验文件大小是否合法
     @return ret true:合法 false:非法
     */
    public function checkSize(){
        $file = $this->file;
        $type = $this->type;
        $validSize = $this->size;
        $ret = true;
        if($type==1){   // 多文件
            foreach($file[‘tmp_name‘] as $v){
                $size = filesize($v);
                if(($size < $validSize[‘min‘]*1024*1024) || ($size > $validSize[‘max‘]*1024*1024)){
                    $ret = false;
                    break;
                }
            }
        }elseif($type==2){  // 单文件
            $size = filesize($file[‘tmp_name‘]);
            if(($size < $validSize[‘min‘]*1024*1024) || ($size > $validSize[‘max‘]*1024*1024)){
                $ret = false;
            }
        }else{  // base64文件
            $size = filesize($file);
            if(($size < $validSize[‘min‘]*1024*1024) || ($size > $validSize[‘max‘]*1024*1024)){
                $ret = false;
            }
        }
        return $ret;
    }
    /*
     内部方法:缩放图片
     */
    private function scale($path,$suffix,$ratio){
        list($width, $height) = getimagesize($path);
        $new_w = $ratio * $width;
        $new_h = $ratio * $height;
        $new_s = imagecreatetruecolor($new_w, $new_h);
        if(in_array($suffix,array(‘jpg‘,‘jpeg‘))){
            $img = imagecreatefromjpeg($path);
        }elseif($suffix == ‘png‘){
            $img = imagecreatefrompng($path);
        }elseif($suffix == ‘gif‘){
            $img = imagecreatefromgif($path);
        }else{
            return false;
        }
        $ret1 = imagecopyresized($new_s, $img, 0, 0, 0, 0, $new_w, $new_h, $width, $height);
        if(in_array($suffix,array(‘jpg‘,‘jpeg‘))){
            $ret2 = imagejpeg($new_s, $path);
        }elseif($suffix == ‘png‘){
            $ret2 = imagepng($new_s, $path);
        }elseif($suffix == ‘gif‘){
            $ret2 = imagegif($new_s, $path);
        }else{
            return false;
        }
        imagedestroy($new_s);
        imagedestroy($img);
        if($ret1 && $ret2){
            return $path;
        }else{
            return false;
        }
    }
    /*
     内部方法:裁剪图片
     */
    private function crop($path,$suffix,$cut_width,$cut_height){
        $cut_x;
        $cut_y;
        $min;
        $size = getimagesize($path);
        $width = $size[0];
        $height = $size[1];
        $min = min($width,$height);
        $cut_width = ($cut_width > $min)?$min:$cut_width;
        $cut_height = ($cut_height > $min)?$min:$cut_height;
        $cut_x = ($width - $cut_width) / 2;
        $cut_y = ($height - $cut_height) / 2;
        if(in_array($suffix,array(‘jpg‘,‘jpeg‘))){
            $img = imagecreatefromjpeg($path);
        }elseif($suffix == ‘png‘){
            $img = imagecreatefrompng($path);
        }elseif($suffix == ‘gif‘){
            $img = imagecreatefromgif($path);
        }else{
            return false;
        }
        $new_s = imagecreatetruecolor($cut_width, $cut_height);
        $ret1 = imagecopyresampled($new_s, $img, 0, 0, $cut_x, $cut_y, $cut_width, $cut_height, $cut_width, $cut_height);
        if(in_array($suffix,array(‘jpg‘,‘jpeg‘))){
            $ret2 = imagejpeg($new_s, $path);
        }elseif($suffix == ‘png‘){
            $ret2 = imagepng($new_s, $path);
        }elseif($suffix == ‘gif‘){
            $ret2 = imagegif($new_s, $path);
        }else{
            return false;
        }
        imagedestroy($new_s);
        imagedestroy($img);
        if($ret1 && $ret2){
            return $path;
        }else{
            return false;
        }
    }
    /*
     内部方法:生成缩略图
     */
    private function thumb($path,$suffix,$cut_width,$cut_height){
        $cut_x;
        $cut_y;
        $ratio = 1;
        $size = getimagesize($path);
        $width = $size[0];
        $height = $size[1];
        $cw;
        $ch;
        if($width/$height >= $cut_width/$cut_height){
            $ratio = $cut_height / $height;
        }else{
            $ratio = $cut_width / $width;
        }
        $path = $this->scale($path,$suffix,$ratio,$path);
        $width *= $ratio;
        $height *= $ratio;
        $cut_x = abs($cut_width - $width) / 2;
        $cut_y = abs($cut_height - $height) / 2;
        if(in_array($suffix,array(‘jpg‘,‘jpeg‘))){
            $img = imagecreatefromjpeg($path);
        }elseif($suffix == ‘png‘){
            $img = imagecreatefrompng($path);
        }elseif($suffix == ‘gif‘){
            $img = imagecreatefromgif($path);
        }else{
            return false;
        }
        $new_s = imagecreatetruecolor($cut_width, $cut_height);
        $ret1 = imagecopyresampled($new_s, $img, 0, 0, $cut_x, $cut_y, $cut_width, $cut_height, $cut_width, $cut_height);
        if(in_array($suffix,array(‘jpg‘,‘jpeg‘))){
            $ret2 = imagejpeg($new_s, $path);
        }elseif($suffix == ‘png‘){
            $ret2 = imagepng($new_s, $path);
        }elseif($suffix == ‘gif‘){
            $ret2 = imagegif($new_s, $path);
        }else{
            return false;
        }
        imagedestroy($new_s);
        imagedestroy($img);
        if($ret1 && $ret2){
            return $path;
        }else{
            return false;
        }
    }
    /*
     保存
     @param dir 存储的文件夹 如:‘./‘
     @return ret 存储的文件路径 如:‘./test.jpg‘
     */
    public function save($dir){
        $file = $this->file;
        $type = $this->type;
        $scale = $this->scale;
        $crop = $this->crop;
        $thumb = $this->thumb;
        $is_scale = $scale[‘is_scale‘];
        $is_crop = $crop[‘is_crop‘];
        $is_thumb = $thumb[‘is_thumb‘];
        $ratio = $scale[‘ratio‘];
        $crop_width = $crop[‘width‘];
        $crop_height = $crop[‘height‘];
        $thumb_width = $thumb[‘width‘];
        $thumb_height = $thumb[‘height‘];
        if($type==1){   // 多文件
            foreach($file[‘tmp_name‘] as $k=>$v){
                $suffix = $this->getSuffix($v);
                $name = $dir.md5(rand(100000,999999)).‘.‘.$suffix;
                $flag = file_put_contents($name,file_get_contents($v));
                if(!$flag){
                    $ret = false;
                }else{
                    if($is_scale){
                        $name = $this->scale($name,$suffix,$ratio);
                    }
                    if($is_crop){
                        $name = $this->crop($name,$suffix,$crop_width,$crop_height);
                    }
                    if($is_thumb){
                        $name = $this->thumb($name,$suffix,$thumb_width,$thumb_height);
                    }
                    $ret[$k] = $name;
                }
            }
        }elseif($type==2){  // 单文件
            $suffix = $this->getSuffix($file[‘tmp_name‘]);
            $name = $dir.md5(rand(100000,999999)).‘.‘.$suffix;
            $flag = file_put_contents($name,file_get_contents($file[‘tmp_name‘]));
            if(!$flag){
                $ret = false;
            }else{
                if($is_scale){
                    $name = $this->scale($name,$suffix,$ratio);
                }
                if($is_crop){
                    $name = $this->crop($name,$suffix,$crop_width,$crop_height);
                }
                if($is_thumb){
                    $name = $this->thumb($name,$suffix,$thumb_width,$thumb_height);
                }
                $ret = $name;
            }
        }else{  // base64文件
            $suffix = $this->getSuffix($file);
            $name = $dir.md5(rand(100000,999999)).‘.‘.$suffix;
            $flag = file_put_contents($name,file_get_contents($file));
            if(!$flag){
                $ret = false;
            }else{
                if($is_scale){
                    $name = $this->scale($name,$suffix,$ratio);
                }
                if($is_crop){
                    $name = $this->crop($name,$suffix,$crop_width,$crop_height);
                }
                if($is_thumb){
                    $name = $this->thumb($name,$suffix,$thumb_width,$thumb_height);
                }
                $ret = $name;
            }
        }
        return $ret;
    }
    }
  • 示例用法:
    $file = $_FILES[‘file‘];
    $fileuploader = new fileuploader($file);
    $fileuploader->thumb = array(
        ‘is_thumb‘=>1,
        ‘width‘=>200,
        ‘height‘=>500
    );
    $ret = $fileuploader->save(‘./‘);
    var_dump($ret);
  • 原文地址:http://blog.51cto.com/12173069/2117631

    时间: 2024-10-09 08:21:22

    php图片上传类(支持缩放、裁剪、图片缩略功能)的相关文章

    html5 图片上传,支持图片预览、压缩、及进度显示,兼容IE6+及标准浏览器

    原文:html5 图片上传,支持图片预览.压缩.及进度显示,兼容IE6+及标准浏览器 以前写过上传组件,见 打造 html5 文件上传组件,实现进度显示及拖拽上传,兼容IE6+及其它标准浏览器,对付一般的上传没有问题,不过如果是上传图片,且需要预览的话,就力有不逮了,趁着闲暇时间,给上传组件添加了单独的图片上传UI,支持图片预览和缩放(通过调整图片的大小以实现图片压缩). 上传组件特点 轻量级,不依赖任何JS库,核心代码(Q.Uploader.js)仅约700行,min版本加起来不到12KB 纯

    图片上传类与加密解密

    php图片上传类 <?php //引入config_app全局变量 include ini_get("yaf.library") ."/../config/application/global.php"; include 'Image.php'; include 'Aes.php'; //获取链接过来的参数 $format = isset($_GET['__format'])?$_GET['__format']:"json"; switch

    在ASP.NET MVC下实现单个图片上传, 客户端服务端双重限制图片大小和格式, 服务端裁剪图片

    在"MVC文件图片ajax上传轻量级解决方案,使用客户端JSAjaxFileUploader插件01-单文件上传"一文中,使用JSAjaxFileUploader这款插件实现了单文件上传,在chrome, firefox下运行良好,但在某些版本的IE浏览器(比如IE8,IE9)下却无法正常运行,这可能是因为JSAjaxFileUploader插件在编写时没有考虑到某些低版本IE浏览器导致的.本篇,就在ASP.NET MVC4下实现单个图片上传,具体功能包括: 1.在客户端选择图片,并限

    PHP图片上传类

    前言 在php开发中,必不可少要用到文件上传,整理封装了一个图片上传的类也还有必要.一.控制器调用 public function upload_file() { if (IS_POST) { if (!empty($_FILES['Filedata'])) { import('Org.Upload', COMMON_PATH); $upload = new \Upload(); // 允许上传文件大小 $upload->allowMaxSize(C('ALLOW_UPLOAD_FILE_MAX

    图片上传类

    1 import java.util.*; 2 import java.lang.*; 3 import java.io.File; 4 import java.util.HashMap; 5 import java.util.List; 6 import java.util.Map; 7 import javax.servlet.http.HttpServletRequest; 8 import org.apache.commons.fileupload.FileItem; 9 import

    CI 图片上传类的解决

    很久没有用CI了,新公司需要用ci ,图片上传的功能,我都搞半天,伤心,因为我是女孩子,给自己找个借口吧. 1. 要看源码,upload.php里do_upload()是上传的主要函数. public function do_upload($field = 'userfile') { // } 默认name = 'userfile',这里要写你自己的name 2.要测试,不能盲目的,盲目的 if (! $this->upload->do_upload ('userfile')) { $erro

    asp.net多图片上传同时保存对每张图片的描述

    前台aspx //图片预览和描述 function previewImage(file) { var div = document.getElementById('preview'); div.innerHTML = ""; for (var i = 0; i < file.files.length; i++) { //alert(file.files[i]); var ndiv = document.createElement("div"); ndiv.st

    php图片上传检测是否为真实图片格式

    PHP 图片上传,如果不做任何判断的话,随便一个文件如 rar,zip,php,java等文件改个文件名,改个后缀就能以图片形式上传的服务器,往往会造成极大的危害! 工具/原料 PHP apache / nginx / iis phpstorm / netbeans / notepad++ / editplus 方法/步骤 1 第一种方法:如果是只是单纯判断是否是图片格式的话,我使用  getimagesize 方法function checkIsImage($filename){    $al

    layui图片上传之后后台如何修改图片的后缀名以及返回数据给前台

    const pathLib = require('path');//引入node.js下的一个path模块的方法,主要处理文件的名字等工作,具体可看文档 const fs = require(''fs); var app = new express(); //前台图片上传访问路径 app.post('/upload',(req,res)=>{ if(Boolean(typeof req.files[0])){//判断访问该后台时是否有图片上传 var ext = pathLib.parse(re