FileReader在ios上面的坑(圖片轉base64)


最近在做項目,傳圖片這是很老的功能了,然后想壓圖片直接傳base64...一開始用的代碼

var fileUpload = function(obj, callback){ //檢測瀏覽器是否支持FileReader對象
            if(typeof FileReader == "undefined"){ alert("您的瀏覽器不支持FileReader對象!"); } var file = obj; //判斷類型是不是圖片
            if(!/image\/\w+/.test(file.type)){ alert("請確保文件為圖像類型"); return false; } var reader = new FileReader(); reader.onload = function (e) { var img = new Image, width = 95,    //圖片resize寬度
                    quality = 0.2,  //圖像質量
                    canvas = document.createElement('canvas'), drawer = canvas.getContext("2d"); img.src = this.result; var scale = parseInt(img.height / img.width); img.width=width; img.height = width * scale; canvas.width = img.width; canvas.height = img.height; drawer.drawImage(testimgId, 0, 0, canvas.width, canvas.height); var base64 = canvas.toDataURL('image/jpeg', 0.2); console.log(base64); var image_base64 = img.src.replace("data:image/png;base64,",""); image_base64=encodeURIComponent(image_base64);
                alert("19") // 調用回調
                callback&&callback(img.src); } reader.readAsDataURL(file); }

上面這段代碼在PC和安卓上運行一切正常,但在ios上會返回固定的一串base64編碼,不管你傳什么圖片都一樣..

然后就改……

再改.....

查看各種文檔..

繼續改...

最后是這樣子決解的

 function getBase64(fileObj){ var file = fileObj, cvs = document.getElementById("canvas"), ctx = cvs.getContext("2d"); if(file){ var url = window.URL.createObjectURL(file);//PS:不兼容IE
                var img = new Image(); img.src = url; img.onload = function(){ ctx.clearRect(0,0,cvs.width,cvs.height); cvs.width = img.width; cvs.height = img.height; ctx.drawImage(img,0,0,img.width,img.height); var base64 = cvs.toDataURL("image/png"); callback(base64); alert("20") } } }

這個才是分享的重點……。

原因就是ios上不支持FileReader對象!


免責聲明!

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



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