2013-04-01 75 views
1

我正在使用Phonegap的相機功能將圖片保存在我的應用程序中。當我嘗試通過保存的file_URI(我從相機獲取)獲取文件時,圖像無法加載。訪問緩存圖片phonegap

 

    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)

的問題出在哪裏可以來自任何想法的緩存文件夾?

回答

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; 
    } 

不要以爲「雖然(BASE64 ==‘’){}」是一個很好的做法,但...

編輯:我用的this gentleman,而不是空的do_when方法循環!