1. 程式人生 > 其它 >Promise圖片路徑轉base64

Promise圖片路徑轉base64

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.dealImage2(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物件傳進去,不能傳路徑