使用PhoneGap,如何获取从iPhone照片库中选择的照片的base64图像数据



使用PhoneGap(Cordova),我试图从照片库中获取照片的base64图像数据。

我可以这样做..当照片是从相机捕获时,在科尔多瓦中使用下面的代码片段。

    navigator.camera.getPicture(onSuccess, onFail, { quality: 50,
    destinationType: Camera.DestinationType.DATA_URL
 }); 
function onSuccess(imageData) {
    var image = document.getElementById('myImage');
    image.src = "data:image/jpeg;base64," + imageData;
}
function onFail(message) {
    alert('Failed because: ' + message);
}

但是,当从库中选择照片时,我应该怎么做才能获取base64图像数据?

function encodeImageUri(imageUri)
{
     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");
     return dataURL;
}

我在PhoneGap中没有解决方案。所以我所需要的只是用户从他们的照片库中选择的图像的base64格式。所以我把那个图像放在画布上,toDataUrl()给了我非常格式:-)

你只需要告诉它从照片库中挑选:

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

请注意,加载大型 base 64 编码图像可能会导致应用中出现内存不足错误。 尽可能使用FILE_URI获取照片。

这是在 base64 中获取图像的好方法,但是此函数何时返回显示 base64 字符串。它向我显示一个白色图像。我的代码如下

var smallImage = document.getElementById('smallImage');
                smallImage.src = encodeImageUri(imageURI);

您可以使用此插件来获取图像的base64编码,它使用iOS的js代码,但是对于android,它使用本机代码来处理低于v.3的android版本,因为低于3的android版本不处理DataUrl功能

试试这个。

function getPhoto(source) {
    // Retrieve image file location from specified source
    navigator.camera.getPicture(onPhotoURISuccess, onFail, { quality: 50,
        destinationType: destinationType.FILE_URI,
        sourceType: source });
} 
function onPhotoURISuccess(imageURI) {
    window.resolveLocalFileSystemURI(imageURI, gotFileEntry, failSystem);
}
function onFail(message) {
    alert('Failed because: ' + message);
}
var gotFileEntry = function(fileEntry) {
   // alert(fileEntry.fullPath);
    console.log("got image file entry: " +  fileEntry.fullPath);
//convert all file to base64 formats
    fileEntry.file( function(file) {
//uncomment the code if you need to check image size
       //if(file.size>(1049576/2))
      // {
           //alert('File size exceeds 500kb');
          // return false;
      // }
        var reader = new FileReader();
        reader.onloadend = function(evt) {
            console.log("Read complete!");
            $('yourimageidtoshow').attr('src',  evt.target.result);
        };
        reader.readAsDataURL(file);
    }, failFile);
};
var failSystem=function(){
    console.log('failed');
}
var failFile=function(){
    console.log('failed');
    throw "toobig";
};

试试这个:https://github.com/brianvandelden/acato-service-image。它使用 imagePicker.git cordova 插件。具有从所选图片中获取图像数据的函数。

相关内容

最新更新