美文网首页
h5 canvas 压缩图片

h5 canvas 压缩图片

作者: code_nerd | 来源:发表于2017-10-27 09:30 被阅读0次
    //js代码
            $(".file-upload").on('change',function() {
                var file = $(this)[0].files[0];
                var url = webkitURL.createObjectURL(file);
                var $img = new Image();
                $img.src = url;
                $img.onload = function() {
                    //生成比例
                    var width = $img.width,
                        height = $img.height,
                        scale = width / height;
                    width = parseInt(800);
                    height = parseInt(width / scale);
    
                    //生成canvas
                    var $canvas = document.createElement("canvas");
                    $canvas.width=width;
                    $canvas.height=height;
                    var ctx = $canvas.getContext('2d');
                    ctx.drawImage($img, 0, 0, width, height);
                    var dataUrl = $canvas.toDataURL('image/png',0.5);
                    var img = dataUrl.replace("data:image/png;base64,", "")
                    //发送到服务端
                    $.post('uploadbase64img',{imgData : img},function(data){
                   
                    },'json');
                }
            });
    
    //服务端代码
            $data = $this->getData(['imgData'=>'string']);
            $img = base64_decode($data['imgData']);
            $file_root = "./uploads/";
        
            if($data['assortment']){
                $file_root.=$data['assortment'].'/';
            }
            $dir = $file_root.date('Y').'/'.date('m').'/'.date('d').'/';//存储路径
            if(!is_dir($dir)){
                mkdir($dir,0777,true);
            }
            $key=uniqid();
            $filename=date('YmdHis').'_'.$key.'.png';
            $result = file_put_contents($dir.$filename, $img);//返回的是字节数
            if($result>0){
                $res[0]['name']=$filename;
                $res[0]['path']=$dir.$filename;
                $res[0]['size']=$result;
                $res[0]['extension']='png';
                $res[0]['key']=$key;
                $this->apiSuccess($res);
            }else{
                //获取上传失败后的错误提示
                $this->apiError(['msg'=>'上传失败']);
            }
            exit;
    
    

    相关文章

      网友评论

          本文标题:h5 canvas 压缩图片

          本文链接:https://www.haomeiwen.com/subject/ggqrpxtx.html