【问题标题】:How to base64 encode an image in javascript如何在javascript中对图像进行base64编码
【发布时间】:2012-10-26 23:16:47
【问题描述】:

我正在开发一个 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)

到目前为止,我已经尝试过Get image data in JavaScript?How can you encode a string to Base64 in JavaScript?

当我尝试以下操作时,

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:, 作为内容。

关于我做错了什么有什么想法吗?

【问题讨论】:

  • 欢迎来到 SQ。第一个问题很好! +1

标签: javascript android image cordova base64


【解决方案1】:

您可以尝试将其作为 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 上实现。

【讨论】:

  • 嗨,Simon,我尝试执行 readAsDataURL 但没有成功。我不想使用 DATA_URL 但我认为它可能是唯一的选择。谢谢。
猜你喜欢
  • 2013-05-30
  • 2018-10-26
  • 1970-01-01
  • 2014-11-18
  • 1970-01-01
  • 2011-04-16
  • 1970-01-01
  • 2021-10-06
  • 1970-01-01
相关资源
最近更新 更多