6

我正在开发一个 phonegap 应用程序并使用该navigator.getPicture方法获取图像。

我得到图片的方式是:

navigator.camera.getPicture(onSuccess, onFail, { quality: 50, 
destinationType: Camera.DestinationType.FILE_URI });

function onSuccess(imageURI) {
    var image = document.getElementById('myImage');
    image.src = imageURI;
}

就像 phonegap 文档中的示例一样。

我希望能够使用 imageURI,然后将其转换为图像数据以便稍后上传。(我不想使用phonegap的FileTransfer)

到目前为止,我已经尝试过在 JavaScript 中获取图像数据?以及如何在 JavaScript 中将字符串编码为 Base64?

当我尝试以下操作时,

function onSuccess(imageURI) {
    getBase64Image(imageURI);
}

function getBase64Image(img) {
    // Create an empty canvas element
    var canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;

    // Copy the image contents to the canvas
    var ctx = canvas.getContext("2d");
   ctx.drawImage(img, 0, 0);

   // Get the data-URL formatted image
   // Firefox supports PNG and JPEG. You could check img.src to
   // guess the original format, but be aware the using "image/jpg"
   // will re-encode the image.
   var dataURL = canvas.toDataURL("image/png");

   console.log(dataURL); //here is where I get 'data:,'       

   return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}

dataURL并在返回前打印。我只是得到data:,内容。

关于我做错了什么的任何想法?

4

1 回答 1

0

好吧,您可以尝试将其作为 DATA_URL 获取。您的里程可能会有所不同,因为当图像转换为 Base64 字符串时,您可能会遇到内存不足错误。

navigator.camera.getPicture(onSuccess, onFail, { quality: 50, 
    destinationType: Camera.DestinationType.DATA_URL });

function onSuccess(imageURI) {
    var image = document.getElementById('myImage');
    image.src = imageURI;
}

或者,您可以使用FileReader.readAsDataURL()

canvas.toDataURL 方法未在早期版本的 Android 上实现。

于 2012-11-07T01:35:12.730 回答