• Promise图片路径转base64


    仓储—索赔单—新增页和修改页:

    可新增6张图片带压缩点击看大图浏览功能,提交全部转为base64;

    修改先把路径赋值到图片框,提交修改时旧图传获取的路径,新图传转换的base64,

    在修改中点新增时将旧图路径转为base64再拼接新图的base64,用了promise和async await,因为路径转base64用到image的onload需要做同步处理

    vue

    async ClaimFormModify_add(){
                var self = this
    
                //上传图片
                var ary = []
                var aryOld = []
                var img = $('#submit_evaluation_commoditylist').find('.zoomImg').filter(function(index,item) {
                    return $(item).attr("src");
                });
    
                //有await不能用each循环
                for(let i=0;i<img.length;i++){
                    let item = img[i]
                    var curSrc = $(item).attr('src')
                    if(curSrc.indexOf('.') == -1){
                        ary.push(curSrc.split(',')[1])
                    }else{
                        var res = await self.dealImage(curSrc)
                        aryOld.push(res)
                        //异步数组为空length为0,但展开有项,有延时问题
                        // self.dealImage(curSrc).then((data)=>{
                        //     aryOld.push(data)
                        // })
                    }
                }
                var OldPicsJson = ''
                var imgBase64 = ''
                //异步此时aryOld没有拿到数据,所以拼接也是空的
                ary = aryOld.concat(ary)//旧新图拼接,所有图都当做新图存
                if(ary.length > 0){
                    imgBase64 = ary.join(';')
                }
    
                // console.log(ary,ary.length);
    
                Ant.showDialog("loding", 1);
                //添加,为当前页面的所有内容提交,页码要累加一次,成功后跳转到第一页
                $.ajax({
                    type: 'POST',
                    url: "/admin/ClaimForm/ClaimForm_AddDetail",
                    data: {
                        StrJson: StrJson
                    },
                    dataType: "json",
                    success: function (msg) {
                        // console.log(msg);
                        if (msg.status.code == "1") {
                            self.curPa = 1
                            self.DetailID = Number(msg.status.sub_msg)
                            if(imgBase64 != ''){
                                //有图片
                                self.uploadImg(imgBase64,OldPicsJson,2)
                            }else{
                                //没图片
                                Ant.showDialog("loding", 0);
                                Ant.alertWindows("提示", "添加成功", 2);
                                self.clearData()
                                self.getDetail()
                            }
    
                        }
                        else {
                            Ant.alertWindows("提示", msg.status.msg, 2);
                        }
                    },
                    error: function (a, b, c) {
    
                    }
                });
    
            },
            //上传图片
            uploadImg:function(imgBase64,OldPicsJson,num){
                var self = this
                $.ajax({
                    type: 'POST',
                    url: "/admin/ClaimForm/ClaimForm_UpPics",
                    data: {
                        ClaimID: self.ClaimID,
                        DetailID: self.DetailID,
                        imgBase64: imgBase64,
                        OldPicsJson: OldPicsJson,
                    },
                    dataType: "json",
                    success: function (msg) {
                        console.log(msg);
                        Ant.showDialog("loding", 0);
                        if (msg.status.code == "1") {
                            if(num == 1){
                                Ant.alertWindows("提示", "修改成功", 2);
                            }else{
                                Ant.alertWindows("提示", "添加成功", 2);
                                self.clearData()
                                self.getDetail()
                            }
                        }
                        else {
                            Ant.alertWindows("提示", msg.status.msg, 2);
                        }
                    },
                    error: function (a, b, c) {
    
                    }
                });
            },
            dealImage: function(path){
                return new Promise((resolve, reject) => {
                    var img = new Image();
                    img.src = path;
                    img.onload = function () {
                        //默认按比例压缩
                        var w = this.width,//img.
                            h = this.height;//img.
                        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.setAttribute("width", w);//anw
                        canvas.setAttribute("height", h);//anh
    
                        ctx.drawImage(this, 0, 0, w, h);
                        // quality值越小,所绘制出的图像越模糊
                        var base64 = canvas.toDataURL('image/jpeg', quality);
                        // 回调函数返回base64的值
                        resolve(base64.split(',')[1])
                    }
                })
            },    

    promise成功后的返回值[[PromiseResult]]中的值如何赋值给变量?

    同步
    async function app(){
        const f1 = ()=>new Promise(r=>r(1))
        let a = await f1()
        console.log(a)
    }
    app()
    
    异步
    function app(){
        const f1 = ()=>new Promise(r=>r(1))
        f1().then(a=>{
            // 变量a的作用域只能在回调内。在外部声明时,因为线程的争夺当前变量的值是不可靠的
            console.log(a)
        })
    }
    如果不在用一个函数体内,请参考监听事件EVENT,当监听到old_data不等于new_data时,实现你的回调逻辑

    图片路径转base64

    // 图片路径
        var img = "imgurl";
    
        function getBase64Image(img) {
            var canvas = document.createElement("canvas");
            canvas.width = img.width;
            canvas.height = img.height;
            var ctx = canvas.getContext("2d");
            ctx.drawImage(img, 0, 0, img.width, img.height);
            var ext = img.src.substring(img.src.lastIndexOf(".")+1).toLowerCase();
            var dataURL = canvas.toDataURL("image/"+ext);
            return dataURL;
        }
        var image = new Image();
        image.src = img;
        console.log(getBase64Image(image));//一定要把image对象传进去,不能传路径
  • 相关阅读:
    手把手教你把华为手机完整备份到NAS
    C#异步编程
    NOIp 走好记
    win11永久关闭实时保护的方法
    BOS解决方案SVN无法签出
    虚拟机VMtools安装驱动失败
    Win11记事本输入多次回车后异常卡死
    清理解决方案_最近开启过的方案
    新增业务员(销售员)选不到特定组织
    readthedocs项目地址
  • 原文地址:https://www.cnblogs.com/liufeiran/p/16173882.html
Copyright © 2020-2023  润新知