几种经过整理的文件上传压缩和前台js压缩的方法

/**
 * 图片压缩上传
 * @param $im,图片资源
 * @param int $maxwidth,最大宽度,超过这个宽度则进行压缩
 * @param int $maxheight,最大高度,超过这个高度则进行压缩
 * @param $name,图片名,完整的路径加名称
 * @param $filetype,图片类型
 * @return bool
 */
function thumbImage($im,$name,$filetype,$maxwidth=800,$maxheight=920)
{
    switch ($filetype) {
        case 'image/jpg':
        case 'image/jpeg':
            $im = imagecreatefromjpeg($im);    //PHP图片处理系统函数  
            break;
        case 'image/gif':
            $im = imagecreatefromgif($im);
            break;
        case 'image/png':
            $im = imagecreatefrompng($im);
            break;
        case 'image/wbmp':
            $im = imagecreatefromwbmp($im);
            break;
    }


    $resizewidth_tag = $resizeheight_tag = false;
    $pic_width = imagesx($im);
    $pic_height = imagesy($im);


    if(($maxwidth && $pic_width > $maxwidth) || ($maxheight && $pic_height > $maxheight))
    {
        $resizewidth_tag = $resizeheight_tag = false;

        if($maxwidth && $pic_width>$maxwidth)
        {
            $widthratio = $maxwidth / $pic_width;
            $resizewidth_tag = true;
        }


        if($maxheight && $pic_height>$maxheight)
        {
            $heightratio = $maxheight / $pic_height;
            $resizeheight_tag = true;
        }


        if($resizewidth_tag && $resizeheight_tag)
        {
            if($widthratio < $heightratio)
                $ratio = $widthratio;
            else
                $ratio = $heightratio;
        }


        if($resizewidth_tag && !$resizeheight_tag)
            $ratio = $widthratio;


        if($resizeheight_tag && !$resizewidth_tag)
            $ratio = $heightratio;


        $newwidth = $pic_width * $ratio;
        $newheight = $pic_height * $ratio;



        if(function_exists("imagecopyresampled"))
        {
            $newim = imagecreatetruecolor($newwidth,$newheight);//PHP图片处理系统函数  
            imagecopyresampled($newim,$im,0,0,0,0,$newwidth,$newheight,$pic_width,$pic_height);//PHP图片处理系统函数  
        }
        else
        {
            $newim = imagecreate($newwidth,$newheight);
            imagecopyresized($newim,$im,0,0,0,0,$newwidth,$newheight,$pic_width,$pic_height);
        }

        switch ($filetype) {
            case 'image/jpg' :
            case 'image/jpeg' :
                $result = imagejpeg($newim,$name);
                break;
            case 'image/gif' :
                $result = imagegif($newim,$name);
                break;
            case 'image/png' :
                $result = imagepng($newim,$name);
                break;
            case 'image/wbmp' :
                $result = imagewbmp($newim,$name);
                break;
        }
        imagedestroy($newim);
    }
    else
    {
        switch ($filetype) {
            case 'image/jpg' :
            case 'image/jpeg' :
                $result = imagejpeg($im,$name);
                break;
            case 'image/gif' :
                $result = imagegif($im,$name);
                break;
            case 'image/png' :
                $result = imagepng($im,$name);
                break;
            case 'image/wbmp' :
                $result = imagewbmp($im,$name);
                break;
        }
    }
    return $result;
}

/**
 * 图片不改变长宽吗,压缩清晰度
 * @param $img,'http://www.phpernote.com/images/logo.png'   或者    public/timg.jpg
 * @param $path, public/frontend/xxx.jpg 保存新图片的地址
 */
function dirthumbImage($img,$filename,$quality=20){
    $imgInfo = pathinfo($img);
    $filetype = $imgInfo['extension'];
    switch ($filetype) {
        case 'gif':
            $image = imagecreatefromgif($img);
            header("Content-type:image/gif");
            break;
        case 'png':
            $image = imagecreatefrompng($img);
            header("Content-type:image/png");
            break;
        case 'wbmp':
            $image = imagecreatefromwbmp($img);
            header("Content-type:image/wbmp");
            break;
        default:
            $image=imagecreatefromjpeg($img);    //PHP图片处理系统函数 jpg、jpeg
            header("Content-type:image/jpeg");
    }
    
    if(empty($filename)) $filename=$img;//如果储存文件为空,那么替换原来的文件
    imagejpeg($image,$filename,$quality); //注意后面那个数字0,这里即压缩等级,参数范围:0-9*/
    imagedestroy($image);
}

/**
 * 将base64编码转换为图片保存至指定位置
 * @param $dir,保存的路径public/frontend/uplode/user
 * @param $filename,图片的名称
 * @param $base64,图片base64编码
 * @param $typeList,允许的图片类型  'jpg', 'png', 'jpeg', 'JPG', 'PNG', 'JPEG','gif','GIF'
 * @return array
 */
function saveBase64($dir,$filename,$base64,$typeList){
    header('Content-type:text/html;charset=utf-8');
    preg_match('/^(data:s*image/(w+);base64,)/', $base64, $result);
    $type = $result[2];    //获取图片的类型jpg png等
    if(empty($typeList)) $typeList = [ 'jpg', 'png', 'jpeg', 'JPG', 'PNG', 'JPEG','gif','GIF'];//文件允许的类型
    if(!in_array($type,$typeList)){
        return array('error'=>2,'msg'=>'图片格式错误');
    }
    $name =$filename.'.'.$type; //图片重命名
    $savepath = $dir.'/'.$name;   //图片保存目录
    if(file_put_contents($savepath, base64_decode(str_replace($result[1], '', $base64)))) {   //对图片进行解析并保存
        return array('error'=>0,'msg'=>'保存成功','file_path'=>$savepath);
    }else{
        return array('error'=>1,'msg'=>'保存失败');
    }
}

function imgToBase64($img_file) {

    $img_base64 = '';
    if (file_exists($img_file)) {
        $app_img_file = $img_file; // 图片路径
        $img_info = getimagesize($app_img_file); // 取得图片的大小,类型等

        //echo '<pre>' . print_r($img_info, true) . '</pre><br>';
        $fp = fopen($app_img_file, "r"); // 图片是否可读权限

        if ($fp) {
            $filesize = filesize($app_img_file);
            $content = fread($fp, $filesize);
            $file_content = chunk_split(base64_encode($content)); // base64编码
            switch ($img_info[2]) {           //判读图片类型
                case 1: $img_type = "gif";
                    break;
                case 2: $img_type = "jpg";
                    break;
                case 3: $img_type = "png";
                    break;
            }

            $img_base64 = $file_content;//合成图片的base64编码

        }
        fclose($fp);
    }

    return $img_base64; //返回图片的base64
}


/**
 * 获取图片的Base64编码(不支持url)
 * @param $img_file 传入本地图片地址
 * @return string
 */
function imgToBase64($img_file) {

    $img_base64 = '';
    if (file_exists($img_file)) {
        $app_img_file = $img_file; // 图片路径
        $img_info = getimagesize($app_img_file); // 取得图片的大小,类型等

        //echo '<pre>' . print_r($img_info, true) . '</pre><br>';
        $fp = fopen($app_img_file, "r"); // 图片是否可读权限

        if ($fp) {
            $filesize = filesize($app_img_file);
            $content = fread($fp, $filesize);
            $file_content = chunk_split(base64_encode($content)); // base64编码
            switch ($img_info[2]) {           //判读图片类型
                case 1: $img_type = "gif";
                    break;
                case 2: $img_type = "jpg";
                    break;
                case 3: $img_type = "png";
                    break;
            }

            $img_base64 = 'data:image/' . $img_type . ';base64,' . $file_content;//合成图片的base64编码

        }
        fclose($fp);
    }

    return $img_base64; //返回图片的base64
}

 JS前台压缩

    //图片上传
    function b(obj,id) {
        var r= new FileReader();
        f=document.getElementById(id).files[0];
        if(f==undefined){return false;}
        r.readAsDataURL(f);
        r.onload=function  (e) {
            //图片压缩
            // 调用函数处理图片                 
            dealImage(this.result, {
// 注意:在pc端可以用绝对路径或相对路径,移动端最好用绝对路径(因为用take photo后的图片路径,我没有试成功(如果有人试成功了可以分享一下经验))
                width : 800
            }, function(base){
//直接将获取到的base64的字符串,放到一个image标签中就可看到测试后的压缩之后的样式图了
                console.log("压缩后:" + base.length / 1024 + " " + base);

            });

        };
    }




/**
 * 图片压缩,默认同比例压缩
 * @param {Object} path
 *   pc端传入的路径可以为相对路径,但是在移动端上必须传入的路径是照相图片储存的绝对路径
 * @param {Object} obj
 *   obj 对象 有 width, height, quality(0-1)
 * @param {Object} callback
 *   回调函数有一个参数,base64的字符串数据
 */
function dealImage(path, obj, callback){
    var img = new Image();
    img.src = path;
    img.onload = function(){
        var that = this;
        // 默认按比例压缩
        var w = that.width,
            h = that.height,
            scale = w / h;
        w = obj.width || w;
        h = obj.height || (w / scale);
        var quality = 0.9;  // 默认图片质量为0.5
        //生成canvas
        var canvas = document.createElement('canvas');
        var ctx = canvas.getContext('2d');
        // 创建属性节点
        var anw = document.createAttribute("width");
        anw.nodeValue = w;
        var anh = document.createAttribute("height");
        anh.nodeValue = h;
        canvas.setAttributeNode(anw);
        canvas.setAttributeNode(anh);
        ctx.drawImage(that, 0, 0, w, h);
        // 图像质量
        if(obj.quality && obj.quality <= 1 && obj.quality > 0){
            quality = obj.quality;
        }
        // quality值越小,所绘制出的图像越模糊
        var base64 = canvas.toDataURL('image/jpeg', quality );
        // 回调函数返回base64的值
        callback(base64);
    }
}

  

原文地址:https://www.cnblogs.com/fpcing/p/8242261.html