Cordova图像选择器转换为base64 [英] Cordova Image Picker convert to base64
问题描述
我无法将图片转换为使用 ngCordova imagePicker
I am having trouble converting an image to base64 format that has been selected using the ngCordova imagePicker.
为了简单起见,Cordova网站上提供的代码如下:
To keep things simple, the code provided on the Cordova site (which works) is this:
module.controller('ThisCtrl', function($scope, $cordovaImagePicker) {
var options = {
maximumImagesCount: 10,
width: 800,
height: 800,
quality: 80
};
$cordovaImagePicker.getPictures(options)
.then(function (results) {
for (var i = 0; i < results.length; i++) {
console.log('Image URI: ' + results[i]);
}
}, function(error) {
// error getting photos
});
});
results数组返回一个结果数组,如:file /// ...但如何转换从这里?我想要一个函数,你传递一个值到(文件),并返回base64字符串。
The results array returns an array of results like: file///... but how to convert from here? I would like a function that you pass in a value to (the file) and returns the base64 string.
这是一个函数,尝试这样:
Here is a function that attempts this:
function convertImgToBase64URL(url, callback, outputFormat){
var canvas = document.createElement('CANVAS'),
ctx = canvas.getContext('2d'),
img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = function(){
var dataURL;
canvas.height = img.height;
canvas.width = img.width;
ctx.drawImage(img, 0, 0);
dataURL = canvas.toDataURL(outputFormat);
callback(dataURL);
canvas = null;
};
img.src = url;
};
但是如何将它集成到代码中?
But how to integrate it into the code?
我试过这个(只需要选择一张图片):
I have tried this (only need to pick one image):
$cordovaImagePicker.getPictures(options)
.then(function (results) {
convertImgToBase64URL(results[0], function(base64Img){
self.chosenImage = base64Img;
});
}, function(error) {
console.log(error);
});
但self.chosenImage设置为空白。
but self.chosenImage gets set to blank.
可能是异步问题,但如何最好地解决它?
Might be an async issue but how best to resolve it?
推荐答案
您可以使用$ cordovaCamera并更改sourceType Camera.PictureSourceType.PHOTOLIBRARY?
Could you use $cordovaCamera and change the sourceType to Camera.PictureSourceType.PHOTOLIBRARY ?
document.addEventListener("deviceready", function () {
var options = {
quality: 50,
destinationType: Camera.DestinationType.DATA_URL,
sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
allowEdit: true,
encodingType: Camera.EncodingType.JPEG,
targetWidth: 100,
targetHeight: 100,
popoverOptions: CameraPopoverOptions,
saveToPhotoAlbum: false
};
$cordovaCamera.getPicture(options).then(function(imageData) {
var image = document.getElementById('myImage');
image.src = "data:image/jpeg;base64," + imageData;
}, function(err) {
// error
});
}, false);
这篇关于Cordova图像选择器转换为base64的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!