1. 程式人生 > >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 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);

}

}