在ios

时间:2016-08-26 14:18:39

标签: javascript ios cordova local-storage localforage

我通过Cordova相机API在ios设备上抓取相机图像,然后通过localforage保存。但是,似乎没有加载资源,因为单击Resources Safari Web Inspector标记下的blob显示An error occured while trying to load resources错误,并且图像呈现为20x20白色背景照片这是围绕Cordova Camera API的HTML包装器:

<head>
    <title>Capture Photo</title>

    <script type="text/javascript" charset="utf-8" src="cordova.js"></script>
    <script type="text/javascript" charset="utf-8" src="js/camera.js"></script>
    <script type="text/javascript" charset="utf-u" src="js/localforage.js"></script>

  <script type="text/javascript">
   function savePhoto(contents){
      localforage.setItem('photo', contents, function(img) {
            // This will be a valid blob URI for an <img> tag.
            var blob = new Blob([img], { type: "image/jpeg" } );
            var imageURI = window.URL.createObjectURL(blob);
            console.log(imageURI);
            var newImg = document.createElement("img");
                newImg.src=imageURI;
                // add the newly created element and its content into the DOM 
                var currentDiv = document.getElementById("div1"); 
                document.body.insertBefore(newImg, currentDiv); 
        });
      console.log(contents.byteLength);
        }

    function grabPhoto(){
      capturePhotoEdit(savePhoto,function(e){console.log(e);});
    }

  </script>

  </head>
  <body>
    <button onclick="grabPhoto();">Capture Photo</button> <br>
    <div id="div1">&nbsp;</div>
  </body>
</html>

我们使用savePhoto来保存从相机中抓取的图像(js/camera.js中)。 blob的控制台日志记录打印出blob:null/916d1852-c8c5-4b3b-ac8c-86b6c71d0e86之类的内容。

我非常感谢指出我在图像渲染方面做错了什么。

1 个答案:

答案 0 :(得分:0)

现在通过切换到&#34; Promise&#34;风格API。不知何故,它不适用于异步回调API版本。修复了以下JS代码:

function savePhoto(contents){

      localforage.setItem('photo', contents).then(function(image) {
            // This will be a valid blob URI for an <img> tag.
            var blob = new Blob([image],{ type:"image/jpeg" });
            console.log('size=' + blob.size);
            console.log('type=' + blob.type);
            var imageURI = window.URL.createObjectURL(blob);
            var newImg = document.createElement("img");
            newImg.src=imageURI;
            newImg.onload = function() {
               URL.revokeObjectURL(imageUrI);
            };
            var currentDiv = document.getElementById("div1"); 
            document.body.insertBefore(newImg, currentDiv); 

        }).catch(function(err) {
          // This code runs if there were any errors
          console.log(err);
        });
}

function grabPhoto(){
  capturePhotoEdit(savePhoto,function(e){console.log(e);});
}