天天看点

angular+ionic 选择手机图库,调用相机,上传图片

angular+ionic 选择手机图库,调用相机,上传图片

1.安装插件 cordova-plugin-image-picker;cordova-plugin-camera;cordova-plugin-file;

2.注入 $cordovaImagePicker;

3.相册选择函数

function sheetImg() {

var options = {

maximumImagesCount: 10, //最大选择图片数量

width: 800, //筛选宽度:如果宽度为0,返回所有尺寸的图片

height: 800, //筛选高度:如果高度为0,返回所有尺寸的图片

quality: 80 //图像质量的大小,默认为100

};

$cordovaImagePicker.getPictures(options).then(function (results) {

for (var i = 0; i < results.length; i++) {

//alert('Image URI: ' + results[i]);

$scope.img_src.push(results[i]);

}

},function(error) {

});

};

4.相机拍照函数

function onDeviceReady() {

var options = {//相机配置

//这些参数可能要配合着使用,比如选择了sourcetype是0, //destinationtype要相应的设置

quality: 80, //相片质量0-100

destinationType: Camera.DestinationType.FILE_URI, //返回类型:DATA_URL= 0,返回作为 base64 編碼字串。 FILE_URI=1,返回影像档的 URI。NATIVE_URI=2,返回图像本机URI (例如,資產庫)

sourceType: Camera.PictureSourceType.CAMERA, //从哪里选择图片:PHOTOLIBRARY=0,相机拍照=1,SAVEDPHOTOALBUM=2。0和1其实都是本地图库

allowEdit: false, //在选择之前允许修改截图

encodingType: Camera.EncodingType.JPEG, //保存的图片格式: JPEG = 0, PNG = 1

targetWidth: 200, //照片宽度

targetHeight: 200, //照片高度

mediaType: 0, //可选媒体类型:圖片=0,只允许选择图片將返回指定DestinationType的参数。 視頻格式=1,允许选择视频,最终返回 FILE_URI。ALLMEDIA= 2,允许所有媒体类型的选择。

cameraDirection: 0, //枪后摄像头类型:Back= 0,Front-facing = 1

popoverOptions: CameraPopoverOptions,

saveToPhotoAlbum: true

}

navigator.camera.getPicture(

function(res){

$scope.img_src.push(res);

}, function(res){

alert("选择失败");

}, options);

}

5.图片上传upImage(图片路径)

// imageUrl 为本地上传图片路径数组

var upImage = function (imageUrl) {

var img_arr = [];

for (var i = 0; i < imageUrl.length; i++) {

$ionicLoading.show({

template: '

上传中...'

});

document.addEventListener('deviceready', function () {

var url = "http://api.maidanfan.la/UserApp/index/uploadImg";

var options = {};

$cordovaFileTransfer.upload(url, imageUrl[i], options)

.then(function (result) {

//alert(JSON.stringify(result));

var res = eval('(' + result.response + ')');

img_arr.push("http://api.maidanfan.la/Uploads/" + res.data.savepath + res.data.savename);

if (imageUrl.length == img_arr.length) { //上传成功

submitDataFun(img_arr); //调用上传提交

}

}, function (err) {

//alert(JSON.stringify(err));

alert("fail");

}, function (progress) {

// constant progress updates

});

$ionicLoading.hide();

}, false);

}

}

继续阅读