科尔多瓦相机,拍不出照片

时间:2015-04-16 13:02:35

标签: android cordova camera

我正在构建一个cordova应用程序,但我无法让相机正常工作。

我的目的是拍照,展示并最终保存。 这是我的代码:

JS

 67 <script>
 68 var sPicData; //store image data for image upload functionality
 69
 70 function capturePhoto(){
 71     navigator.camera.getPicture(picOnSuccess, picOnFailure, {
 72         quality: 20,
 73         destinationType: Camera.DestinationType.DATA_URL,
 74         sourceType: Camera.PictureSourceType.CAMERA,
 75         correctOrientation: true
 76     });
 77 }
 78
 79 function getPhoto(){
 80     //navigator.camera.getPicture(picOnSuccess, picOnFailure, {
 81     //    quality: 20,
 82     //    destinationType: Camera.DestinationType.DATA_URL,
 83     //    sourceType: Camera.PictureSourceType.SAVEDPHOTOALBUM,
 84     //    correctOrientation: true
 85     //});
 86     navigator.camera.getPicture(picOnSuccess, picOnFailure, {
 87         quality: 20
 88     });
 89 }
 90
 91 function picOnSuccess(imageData){
 92         var image = document.getElementById('cameraPic');
 93         alert(image);
 94         image.style.dispay = 'block';
 95         image.src = imageData;
 96         sPicData  = imageData; //store image data in a variable
 97 }
 98
 99 function picOnFailure(message){
100     alert('Failed because: ' + message);
101 }
102 </script>

HTML

 44 <div id="camera">
 45     <button class="camera-control" onclick="capturePhoto();">Foto aufnehmen</button>
 46     <button class="camera-control" onclick="getPhoto();">From Photo Library</button><br>
 47
 48     <div style="text-align:center;margin:20px;">
 49         <img id="cameraPic" src="" style="width:auto;height:120px;"></img>
 50     </div>
 51
 52     <button class="camera-control" onclick="photoUpload();">UPLOAD</button>
 53 </div>

结果是我可以拍摄照片,但结果div如下:

<img id="cameraPic" src="/9j/lots_of_non_sense_stuff///Z" style="width:auto;height:120px;">

在该行上出现此错误:

Failed to load resource: net::ERR_FILE_NOT_FOUND file:///9j/4AAQSkZJRgABAQAAAQABAAD/2wBDACgcHiMeGSgjISMtKygwPGRBPDc3PHtYXUlk…ACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD//Z

我错过了什么吗?

1 个答案:

答案 0 :(得分:2)

图像数据以base64格式返回。要正确显示它,您必须告诉浏览器图像源不是文件,而是base64编码的数据:

function picOnSuccess(imageData){
         var image = document.getElementById('cameraPic');
         alert(image);
         image.style.dispay = 'block';
         image.src = "data:image/jpeg;base64," + imageData;
         sPicData  = imageData; //store image data in a variable
}

另一个解决方案是让cordova将图片保存到文件中:

function capturePhoto(){
     navigator.camera.getPicture(picOnSuccess, picOnFailure, {
         quality: 20,
         destinationType: Camera.DestinationType.FILE_URI,
         sourceType: Camera.PictureSourceType.CAMERA,
         correctOrientation: true
     });
}

使用此方法,将通过其imageData参数中的临时文件路径调用success函数,以便您可以使用以前的代码。参见文档:

http://docs.phonegap.com/en/edge/cordova_camera_camera.md.html