H5,php处理图片压缩上传

28 篇文章 0 订阅

前端代码 

function readFile(obj){ 
    var file = obj.files[0];  
    //判断类型是不是图片 
    if(!/image\/\w+/.test(file.type)){ 
        alert("请确保文件为图像类型"); 
        return false; 
    } 
    var objUrl = getObjectURL(file) ; //获取图片的路径,该路径不是图片在本地的路径
    if (objUrl) {
        $(".simg").css("display","inline-block");
        $(".simg img").eq(0).attr("src", objUrl) ; //将图片路径存入src中,显示出图片
	  }
    var reader = new FileReader(); 
    reader.readAsDataURL(file); 
    reader.onload = function(e){
      dealImage(this.result,{width:260},function(base){
        var data={
            'image':base
        };
        post("{:url('api/upload/base64')}",data,callpay,'','',''); 
        function callpay(res){


    
        }
      });
    } 
} 
  /**
   * 图片压缩,默认同比例压缩
   * @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.7; // 默认图片质量为0.7
   //生成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 );
    var base64 = canvas.toDataURL('image/gif', quality );
    // 回调函数返回base64的值
    callback(base64);
   }
}

php 接收base64

    public function base64(Request $request){
        $param = $request->param();
        //目录的upload文件夹下
        $up_dir = "./static/uploads/".date('Ymd', time()) . "/";  //创建目录
        if(!file_exists($up_dir)){
            mkdir($up_dir,0777,true);
        }
        $base64_img = trim($param['image']);
 
        if(preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_img, $result)){
            $type = $result[2];
            if(in_array($type,array('pjpeg','jpeg','jpg','gif','bmp','png'))){
                $new_file = $up_dir.time().'.'.$type;
                if(file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_img)))){
                    $img_path = str_replace('../../..', '', $new_file);
                    $data=[
                        'url'        =>str_replace("./static/uploads",'',$img_path), 
                        'created_at' => time()
                    ];
                    $image=Db::name('images')->insert($data);
                    $img_id=Db::name('images')->getLastInsID();
                    return Json([
                        'code'=>1,
                        'msg' =>'上传图片成功',
                        'data'=>[
                            'img_id'=>$img_id,
                            'url'   =>getImgUrlById($img_id)
                        ]
                    ]);
                }else{
                    return Json([
                        'code'=>0,
                        'msg'=>"上传图片失败,请稍后重试"
                    ]);
                }
            }else{
                //文件类型错误
                return Json([
                    'code'=>0,
                    'msg'=>'图片上传类型错误'
                ]);
            }
        }
    }

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值