layui在上传图片在前端处理图片压缩

有的人会遇到需要在前端代码处理图片压缩的问题,下面给大家分享怎么处理。

// 上传图片

var image_src

var IsImgDeal=false;

layui.upload.render({

    elem: "#{tag}{id}",

    url: sessionStorage.getItem('httpUrlPrefix') + '/upload/uploadImage',

    // dataType: 'text',

    // auto: false,

    // multiple: true,

    accept:"images",

    exts: 'jpg|png|jpeg',

    acceptMime:"image/jpeg,image/png",

    before: function (obj) {

        layer.msg("图片上传中...", { icon: 16, shade: 0.01 })

    },

    done: function(res){

         layer.msg(`

                                               提示

                                               

                                             

                                             
上传成功!

`

            , {

                skin: 'success-class',

                time: 1000

            });

             layer.closeAll('loading'); //关闭loading

        console.log("sfafasfa",JSON.stringify(res))

        image_src = res.url

        IsImgDeal = false;

    },

    choose: function (obj) {

        obj.preview(function (index, file, result) {

            console.log("================>",file)

            let filename = file.name

            // console.log("================>",result)

            //临时存储二进制流

            $("#uploadnewImg-{id}").hide()

            $("#uploadexistimg-{id}").show()

            $("#uploadImg-{id}").attr("src", result);

        });

if (IsImgDeal) {

                        return;//图片处理过就直接上传

                    }

                    console.log("图片压缩开始处理");

                    var files = obj.pushFile();

                    var file_tar = null,index_tar = null;

                    for (var k in files) {

                        index_tar = k;

                        file_tar = files[k];

                        break;

                    }

                    

                    

                    //进行图片压缩,直接百度压缩方法

                    let reader = new FileReader();

                    var filename = file_tar.name;

                    

                    reader.readAsDataURL(file_tar);

                    

                    reader.onload = function () {

                        

                        let content = this.result; //图片的src,base64格式

                        let img = new Image();

                        img.src = content;

                        img.onload = function () { //图片加载完毕

                            

                            let canvas = document.createElement("canvas");

                            let ctx = canvas.getContext('2d');

                            

                            let width = Math.ceil(img.width*0.8);

                            let height = Math.ceil(img.height*0.8);

                            canvas.width = width;

                            canvas.height = height;

                            ctx.drawImage(img, 0, 0, width, height);//压缩图片尺寸

                            let dataURL = canvas.toDataURL("image/jpeg");//如果是需要质量压缩就补充参数

                            //将base64数据转化为文件对象

                            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);

                            }

                            IsImgDeal = true;//设置标记

                            //如果有时差问题,后面setTimeout延时再执行,让原来的上传终止

                            obj.upload(index_tar, new File([new Blob([u8arr], { type: mime })], filename));//单独上传

                            

                            //uploadIns.upload();//重新启动全部文件上传

                        }

                    };

                   layer.load(); //上传loading

                    //停止原本的上传,如果多个文件,需要在读取完毕后将files里面的文件队列全删除。

                    return delete files[index_tar];

        

    },

});

你可能感兴趣的:(layui,前端,javascript)