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