【问题标题】:How to get Base 64 string instead of imageURI in Phonegap while selecting image from Photo library从照片库中选择图像时如何在Phonegap中获取Base 64字符串而不是imageURI
【发布时间】:2013-09-25 13:16:14
【问题描述】:

我目前正在使用以下函数从照片库中获取图像

function getImage() {
    // Retrieve image file location from specified source
    navigator.camera.getPicture(updatePhoto, function(message) {
                                alert('get picture failed');
                                },{
                                quality: 50,
                                destinationType: navigator.camera.DestinationType.FILE_URI,
                                sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY
                                }
                                );

}

function updatePhoto(imageURI) {

    //console.log(imageURI);

}

但现在我想要 base64 字符串而不是图像 URL!

如何做到这一点?

【问题讨论】:

    标签: ios cordova base64


    【解决方案1】:

    更改以下代码
    destinationType: navigator.camera.DestinationType.FILE_URI,
    

    destinationType: Camera.DestinationType.DATA_URL
    

    请点击此链接phonegap

    【讨论】:

      【解决方案2】:

      我们发现,在 Worklight 中甚至不存在 navigator.camera.getPicture()。 但是, navigator.device.capture.captureImage() 有效,并且具有相同的签名。 无论目标类型如何设置,它总是返回一个文件 URI。在 iOS 上,它实际上返回一个图像数组,如下所示: [ { "name": "photo_008.jpg", "fullPath": "/var/mobile/Applications/5585AC9F-27AF-46B1-AEA1-A2DFE​​01C218F/tmp/photo_008.jpg", “类型”:“图像/JPEG”, "lastModifiedDate": 1400008865000, “大小”:1000708, “开始”:0, “结束”:0 } ]

      要自己将此 URI 转换为 base 64,您可以按照以下过程: 1 - 创建一个临时的隐藏画布 2 - 将图像渲染到画布上 3 - 从画布中导出base64编码的图像数据

      可以执行此操作的实用程序可能如下所示:

      function encodeImageUri(imageUri)
      {
          // My apologies as I can't recall where I found this snippet. But it works well!
          var c=document.createElement('canvas');
          var ctx=c.getContext("2d");
          var img=new Image();
          img.onload = function(){
              c.width=this.width;
              c.height=this.height;
              ctx.drawImage(img, 0,0);
          };
          img.src=imageUri;
          var dataURL = c.toDataURL("image/jpeg");
      
          console.log("Encoded the data at " + imageUri + " to base64: " + dataURL);
          return dataURL;
      }
      

      【讨论】:

        猜你喜欢
        • 2012-06-26
        • 1970-01-01
        • 2017-09-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-01-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多