我正在使用Phonegap的相机功能在我的应用程序中保存图片。当我尝试通过其保存的file_URI(我从相机获取)获取文件时,图像不会加载。
function toBase64(url) { var canvas = document.createElement("canvas"); var ctx = canvas.getContext('2d'); var img = new Image(); img.src = url; if ( img.height != 0 ) { var height = img.height, width = img.width; canvas.height = height; canvas.width = width; ctx.drawImage(img, 0, 0, width, height); try { var dataURL = canvas.toDataURL("image/jpg"); return dataURL.replace(/^data:image\/(png|jpg);base64,/, ""); } catch (err) { console.log("ERROR " + err);} } else { alert("Wrong path!"); } }
图像保存在应用程序的缓存文件夹中(/data/data/my.app/cache)
有关问题出在何处的任何想法?
答案 0 :(得分:2)
我解决了这个问题,不得不使用Phonegap的FileReader对象。
var base64; function toBase64(filename) { window.requestFileSystem(LocalFileSystem.TEMPORARY, 0, function(fileSystem) { // Filesystem's root is the cache folder of the application: /storage/emulated/0/Android/data/com.yourcompany.whatever fileSystem.root.getFile(filename, null, function(fileEntry) { fileEntry.file(function(file) { var reader = new FileReader(); reader.onloadend = function(evt) { console.log(evt.target.result); // Firing callback base64 = evt.target.result; }; reader.readAsDataURL(file); }, fail); }, fail); }, fail); // We wait until the reader was fully loaded and then we return the base64 encrypted data ! while ( base64 == "" ) {} base64 = base64.replace(/^data:image\/(png|jpg|jpeg);base64,/, ""); return base64; }
不要认为“while(base64 ==”“){}”虽然是一个很好的做法......
编辑:我使用了this gentleman的do_when方法而不是空循环!