开发App的时候会经常用到拍照上传留作凭证,或者从图库中选择。
相关插件:
相机:cordova-plugin-camera 2.4.1
图库:cordova-plugin-image-picker 1.1.1
文件:cordova-plugin-file
权限:cordova-plugin-android-permissions 1.0.0
安装权限插件主要是因为Android8.0以上的版本有权限限制。
1 安装插件
cordova plugin add cordova-plugin-camera
cordova plugin add cordova-plugin-image-picker
cordova plugin add cordova-plugin-file
cordova pluign add cordova-plugin-android-permissions
2 相关权限代码:
```
function checkPermissions() {
const permissions = cordova.plugins.permissions,
permissionList = [permissions.CAMERA,
permissions.WRITE_EXTERNAL_STORAGE,
permissions.INSTALL_LOCATION_PROVIDER];
function errorCallbacks() {
console.warn("permissions is not turned on");
}
function checkPermissionCallbacks(status) {
if(!status.hasPermission) {
permissions.requestPermissions(
permissionList,
status => {
if(!status.hasPermission) errorCallbacks();
},
errorCallbacks);
}
}
permissions.hasPermission(permissionList, checkPermissionCallbacks, null);
}
checkPermissions()
```
2 相关html代码
```
<button ng-click="useCamera()">调用摄像机</button>
<img src="" id="myImage"/>
<button class="button button-full button-calm" ng-click="takePhoto1(str,data)">从相册选择</button>
<img src="{{mess}}" alt="">
```
3 相关controller 代码
拍照上传
```
$scope.useCamera=function(){
var options = {
quality: 50, //照片质量
destinationType: Camera.DestinationType.DATA_URL, //base64编码图像
sourceType: Camera.PictureSourceType.CAMERA, //图像来源
allowEdit: true, //是否允许编辑
encodingType: Camera.EncodingType.JPEG, //保存的图片格式
targetWidth: 100, //最大宽度
targetHeight: 100, //最大高度
popoverOptions: CameraPopoverOptions,
saveToPhotoAlbum: true //是否保存到相册
};
$cordovaCamera.getPicture(options).then(function(imageData) {
var image = document.getElementById('myImage');
image.src = "data:image/jpeg;base64," + imageData;
}, function(err) {
// error
});
}
```
从图库中选择
```
$scope.takePhoto1 = function(){//打开相册
var options = {
maximumImagesCount: 3,
width: 200,
height: 200,
quality: 100
};
$cordovaImagePicker.getPictures(options)
.then(function (results) {
// for (var i = 0; i < results.length; i++) {
// var sss = $scope.getImageToBase64(results[i]);
// alert($scope.getImageToBase64(results[i]));
// $scope.img_src.push(sss);
// }
convertImgToBase64URL(results[0], function(base64Img){
self.chosenImage = base64Img;
$scope.mess = self.chosenImage
});
}, function(error) {
$scope.data.push(error);
});
};
```
转化base64位
```
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;
};
```