美文网首页
1.前端上传图片前压缩并预览

1.前端上传图片前压缩并预览

作者: 一枼落知天下 | 来源:发表于2019-08-10 11:22 被阅读0次

    利用canvas实现保存图片时,拼上二维码的需求

    前端代码

    <div class="fullface @if(isset($qyInfo['qyInfo']['front_url'])) on @endif">
                              <i></i>
                                <p><span>点击上传</span>营业执照</p>
                                <input class="uploadfile" type-img="front" name="mypic" type="file">
                                <img src="{{isset($qyInfo['qyInfo']['front_url'])?$qyInfo['qyInfo']['front_url']:''}}" id="front_url" alt="正面">
                            </div>
      <script>
        // 存储处理过的文件对象
        var filelist = {};
        //将base64转换为文件
        function dataURLtoFile(dataurl, filename) {
            var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
                bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
            while(n--){
                u8arr[n] = bstr.charCodeAt(n);
            }
            return new File([u8arr], filename, {type:mime});
        }
    
        $(function () {
            // 表单数据提交
            $('.authentication_submit').click(function(){
                //获取数据
                var realname = $('#realname').val();
                var realname_reg = /^[\u4E00-\u9FA5\uF900-\uFA2D]{2,6}$/;
                var idcard = $('#idcard').val();
                var copm_name = $('#copm_name').val();
               // var idcard_reg = /^(\d{6})+(\d{4})+(\d{2})+(\d{2})+(\d{3})([0-9]|X)$/;
                var front_url = $('#front_url').attr('src');
                //验证身份证姓名
                if(!realname_reg.test(realname)){
                    layer.msg('只能输入2-6位的姓名',{icon:0});
                    return;
                }
                //验证社会信用代码
                if(idcard.length <=0){
                    layer.msg('请输入统一社会信用代码',{icon:0});
                    return;
                }
                if(idcard.length <=0){
                    layer.msg('请输入统一社会信用代码',{icon:0});
                    return;
                }
                //验证身份证正面
                if(copm_name.length <=0){
                    layer.msg('请填写企业名称',{icon:0});
                    return;
                }
                if(front_url.length <=0){
                    layer.msg('请上传营业执照正面',{icon:0});
                    return;
                }
    
                var formData = new FormData();
                formData.append('realname',realname);
                formData.append('idcard',idcard);
                formData.append('copm_name',copm_name);
                formData.append('front_url',front_url);
                formData.append('_token',$('#_token').val());
                // 将文件添加到form表单里面,发送给后台
                for (let key in filelist){
                    formData.append(key,filelist[key]);
                }
    
                // 将数据发送给后台~上传保存到七牛,保存实名信息
                $.ajax({
                    url: '/userCenter/certification_qy_update' ,
                    type: 'POST',
                    data: formData,
                    async: false,
                    cache: false,
                    contentType: false,
                    processData: false,
                    success: function (data) {
                        var data = eval("(" + data + ")");
                        if(data.status ==1){
                            layer.msg(data.msg,{icon:1});
                            setTimeout(function () {
                                window.location.href = '/userCenter';
                            },1500)
                        }else {
                            layer.msg(data.msg,{icon:0});
                        }
                    },
                    error: function (data) {
                        layer.msg(data,{icon:0});
                    }
                });
    
            });
    
            // 保存 压缩过的图片对象
            $(".uploadfile").change(function (ev) {
                var filename ;
                var fileMaxSize = 1024*2;//2M
                var quality = 0.62; // 图像质量
                var _this = $(this);
                var imgType = $(this).attr('type-img');
                //判断 FileReader 是否被浏览器所支持
                if (!window.FileReader) return;
                var file = ev.target.files[0];
                if (!file) {
                    layer.msg('上传失败,请重新操作!', {icon: 0, shade: [0.3, '#393D49'], shadeClose: true});
                    return;
                }
                filename = file.name;
    
                //判断图片格式~
                if (!file.type.match('image/*')) {
                    layer.msg('请选择格式为(jpg、png、jpeg)的图片文件!', {icon: 0, shade: [0.3, '#393D49'], shadeClose: true});
                    ev.target.value = ""; //显示文件的值赋值为空
                    return;
                }
    
                //file.size 文件字节数
                if ((file.size / 1024) > fileMaxSize) {
                    layer.msg('请选择小于2M的图片!', {icon: 0, shade: [0.3, '#393D49'], shadeClose: true});
                    ev.target.value = ""; //显示文件的值赋值为空;
                    return;
                }
    
                var _image = new Image();
                // 创建FileReader对象
                var reader = new FileReader();
                // 读取file对象,读取完毕后会返回result 图片base64格式的结果
                reader.readAsDataURL(file);
                reader.onload = function (e) {
                    _image.src = e.target.result
                }
    
                // 图片压缩,加水印,
                _image.onload = function () {
                    if (this.complete) {
                        var canvas = document.createElement('canvas');
                        canvas.width = _image.width
                        canvas.height = _image.height
                        var ctx = canvas.getContext("2d");
                        ctx.drawImage(_image, 0, 0, _image.width, _image.height);
                        // ctx.font = "20px microsoft yahei";
                        // ctx.fillStyle = "rgba(255,255,255,0.5)";
                        // ctx.fillText('zhoushuai',30,30);
    
                        //base64文件
                        var dataUrl = canvas.toDataURL(file.type, quality);
                        //将base64转换为文件对象
                        var fileObj = dataURLtoFile(dataUrl,filename);
                        //全局对象保存文件
                        filelist[imgType] = fileObj;
    
                        canvas.toBlob(function (blob) {
                            var url = '';
                            if (window.createObjectURL !== undefined) {
                                url = window.createObjectURL(blob)
                            } else if (window.URL !== undefined) {
                                url = window.URL.createObjectURL(blob)
                            } else if (window.webkitURL !== undefined) {
                                url = window.webkitURL.createObjectURL(blob)
                            }
                            _this.next('img').attr('src', url);
                            _this.parent('div').addClass('on');
                        }, file.type, quality);
                    }
                }
    
    
    
                /*var _this = $(this);
                var formData = new FormData();
                var file =_this.context.files[0];
                var _token = $('#_token').val();
                formData.append('mypic',file);
                formData.append('_token',_token);
                $.ajax({
                    url: "/userCenter/uploadFile",
                    data: formData,
                    type: "Post",
                    dataType: "json",
                    contentType: false,
                    /!**
                     * 必须false才会避开jQuery对 formdata 的默认处理
                     * XMLHttpRequest会对 formdata 进行正确的处理
                     *!/
                    processData: false,
                    success: function (data) {
                        if(data.status ==1){
                            _this.next('img').attr('src',data.pic);
                            _this.parent('div').addClass('on');
                        }else {
                            alert(data.msg);
                        }
                    }
                })*/
            });
        });
    
    </script>
    

    后端代码:

       /**
         * @author Jhou Shuai
         * @desc 实名认证数据整理、证件照上传
         */
        private function certDataHandle(&$data){
            // 过滤掉不需要的数据。方便入库
            unset($data['code']);
            unset($data['_token']);
            unset($data['front']);
            unset($data['back']);
            unset($data['hold']);
    
            // 证件照上传
            if(isset($_FILES)){
                $img = new Image();
                foreach ($_FILES as $key=>$file){
                    $result = $img->uploadImage($file);
                    if(isset($result['error'])){
                        $infos['status'] = 0;
                        $infos['msg'] = $result['error'];
                        die(json_encode($infos));
                    }
                    $index = $key."_url";
                    $data[$index] = $result;
                }
            }
        }
    
    public function certification_qy_update(Request $request){
            //获取实名认证的参数
            $user = Session::get('yd_user');
            $data = $request->all();
    
            //实名认证数据整理、证件照上传
            $this->certDataHandle($data);
           // 此处省略三千字...
    }
    
    

    相关文章

      网友评论

          本文标题:1.前端上传图片前压缩并预览

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