圖片文件轉換成Base64編碼實現ajax提交圖片


                //上傳頭像圖片 
        function uploadHead(imgPath) {
            console.log("imgPath = " + imgPath);
            var image = new Image();
            image.onload = function() {
                var imgData = getBase64Image(image);
                /*在這里調用上傳接口*/
                mui.ajax($serverPath + "app/modifyHead", {
                    data: {
                        'imgData': imgData,
                        'userId': plus.storage.getItem("userId")
                    },
                    dataType: 'json',
                    type: 'post',
                    timeout: 10000,
                    success: function(data) {
                        if(data.result == 'yes') {
                            $newHead = data.newHeadPath;
                            console.log('上傳成功!!!!!!!!!!' + $newHead);
                            plus.storage.setItem("userHead", $newHead);
                            mui.toast("頭像修改成功!");
                        } else {
                            mui.toast("頭像上傳失敗!");
                        }
                    },
                    error: function(xhr, type, errorThrown) {
                        mui.toast('網絡異常,請稍后再試!');
                    }
                });
            }
            image.src = imgPath;
            image.style.width = "60px";
            image.style.height = "60px";
            console.log("haha");
        }
        //將圖片壓縮轉成base64 
        function getBase64Image(img) {
            var canvas = document.createElement("canvas");
            var width = img.width;
            var height = img.height;
            // calculate the width and height, constraining the proportions 
            if(width > height) {
                if(width > 100) {
                    height = Math.round(height *= 100 / width);
                    width = 100;
                }
            } else {
                if(height > 100) {
                    width = Math.round(width *= 100 / height);
                    height = 100;
                }
            }
            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.8);
            return dataURL.replace("data:image/png;base64,", "");
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM