效果演示
源代碼已上傳到github
由于ionic版本更新較快,有些寫法可能改變來不及更新簡書,請以github代碼為準(zhǔn)
ionic2.0插件的使用方式和ionic3.0已不一樣
安裝插件
- 安裝cordova-plugin-camera插件,安裝過程如下圖
- 我在第一次執(zhí)行
ionic platfrom add android
時拋出了一個異常,解決了,異常詳情看這里 - 當(dāng)執(zhí)行
ionic platfrom add android
,沒有問題時,說明我們的環(huán)境沒有問題啦.然后在寫代碼.
封裝拍照插件
- 第一步我在src根目錄新建一個providers文件夾,在這個文件夾新建一個
NativeService.ts
文件,叫NativeService是因為這個ts專門寫app所有插件相關(guān)的代碼,不止只有拍照插件 -
NativeService.ts
完整代碼如下
這里是ionic2.0插件的使用方式.ionic3.0使用方式看這里
/**
* Created by yanxiaojun617@163.com on 01-03.
*/
import {Injectable} from '@angular/core';
import {ToastController, LoadingController} from 'ionic-angular';
import {Camera} from 'ionic-native';
@Injectable()
export class NativeService {
private toast;
private loading;
constructor(private toastCtrl: ToastController, private loadingCtrl: LoadingController) {
}
/**
* 統(tǒng)一調(diào)用此方法顯示提示信息
* @param message 信息內(nèi)容
* @param duration 顯示時長
*/
showToast = (message: string = '操作完成', duration: number = 2500) => {
this.toast = this.toastCtrl.create({
message: message,
duration: duration,
position: 'top',
showCloseButton: true,
closeButtonText: '關(guān)閉'
});
this.toast.present();
};
/**
* 關(guān)閉信息提示框
*/
hideToast = () => {
this.toast.dismissAll()
};
/**
* 統(tǒng)一調(diào)用此方法顯示loading
* @param content 顯示的內(nèi)容
*/
showLoading = (content: string = '') => {
this.loading = this.loadingCtrl.create({
content: content
});
this.loading.present();
setTimeout(() => {//最長顯示20秒
this.loading.dismiss();
}, 20000);
};
/**
* 關(guān)閉loading
*/
hideLoading = () => {
this.loading.dismissAll()
};
/**
* 使用cordova-plugin-camera獲取照片的base64
* @param options
* @return {Promise<T>}
*/
getPicture = (options) => {
return new Promise((resolve, reject) => {
Camera.getPicture(Object.assign({
sourceType: Camera.PictureSourceType.CAMERA,//圖片來源,CAMERA:拍照,PHOTOLIBRARY:相冊
destinationType: Camera.DestinationType.DATA_URL,//返回值格式,DATA_URL:base64,FILE_URI:圖片路徑
quality: 90,//保存的圖像質(zhì)量润文,范圍為0 - 100
allowEdit: true,//選擇圖片前是否允許編輯
encodingType: Camera.EncodingType.JPEG,
targetWidth: 800,//縮放圖像的寬度(像素)
targetHeight: 800,//縮放圖像的高度(像素)
saveToPhotoAlbum: false,//是否保存到相冊
correctOrientation: true//設(shè)置攝像機拍攝的圖像是否為正確的方向
}, options)).then((imageData) => {
resolve(imageData);
}, (err) => {
console.log(err);
err == 20 ? this.showToast('沒有權(quán)限,請在設(shè)置中開啟權(quán)限') : reject(err);
});
});
};
/**
* 通過圖庫獲取照片
* @param options
* @return {Promise<T>}
*/
getPictureByPhotoLibrary = (options = {}) => {
return new Promise((resolve) => {
this.getPicture(Object.assign({
sourceType: Camera.PictureSourceType.PHOTOLIBRARY
}, options)).then(imageBase64 => {
resolve(imageBase64);
}).catch(err => {
String(err).indexOf('cancel') != -1 ? this.showToast('取消選擇圖片', 1500) : this.showToast('獲取 照片失敗');
});
});
};
/**
* 通過拍照獲取照片
* @param options
* @return {Promise<T>}
*/
getPictureByCamera = (options = {}) => {
return new Promise((resolve) => {
this.getPicture(Object.assign({
sourceType: Camera.PictureSourceType.CAMERA
}, options)).then(imageBase64 => {
resolve(imageBase64);
}).catch(err => {
String(err).indexOf('cancel') != -1 ? this.showToast('取消拍照', 1500) : this.showToast('獲取照片失敗');
});
});
};
}
- 第二步,把
NativeService.ts
加入到app.module.ts
中,如下圖
使用
我的html頁面代碼
<ion-header>
<ion-toolbar>
<ion-title>
設(shè)置個人頭像
</ion-title>
<ion-buttons start>
<button ion-button (click)="dismiss()">
<span showWhen="ios">關(guān)閉</span>
<ion-icon name="md-close" showWhen="android,windows,landscape"></ion-icon>
</button>
</ion-buttons>
</ion-toolbar>
</ion-header>
<ion-content padding text-center>
<img [src]="avatarPath" width="100%">
<div padding-top>
<button ion-button block color="light" (click)="getPicture(0)">從相冊選一張</button>
</div>
<div padding-top>
<button ion-button block color="light" (click)="getPicture(1)">拍一張照片</button>
</div>
<div padding-top>
<button type="button" ion-button block (click)="saveAvatar()">保 存</button>
</div>
</ion-content>
我的.ts文件代碼
import {Component} from '@angular/core';
import {ViewController} from 'ionic-angular';
import {NativeService} from "../../providers/NativeService";
@Component({
selector: 'page-page2',
templateUrl: 'page2.html'
})
export class Page2Page {
isChange: boolean = false;//頭像是否改變標(biāo)識
avatarPath: string = './assets/img/qr_code.png';//用戶默認頭像
imageBase64: string;//保存頭像base64,用于上傳
constructor(private viewCtrl: ViewController,
private nativeService: NativeService) {
}
getPicture(type) {//1拍照,0從圖庫選擇
let options = {
targetWidth: 400,
targetHeight: 400
};
if (type == 1) {
this.nativeService.getPictureByCamera(options).then(imageBase64 => {
this.getPictureSuccess(imageBase64);
});
} else {
this.nativeService.getPictureByPhotoLibrary(options).then(imageBase64 => {
this.getPictureSuccess(imageBase64);
});
}
}
private getPictureSuccess(imageBase64) {
this.isChange = true;
this.imageBase64 = <string>imageBase64;
this.avatarPath = 'data:image/jpeg;base64,' + imageBase64;
}
saveAvatar() {
if (this.isChange) {
console.log(this.imageBase64);//這是頭像數(shù)據(jù).
this.nativeService.showLoading('正在上傳....');
this.viewCtrl.dismiss({avatarPath: this.avatarPath});//這里可以把頭像傳出去.
} else {
this.dismiss();
}
}
dismiss() {
this.viewCtrl.dismiss();
}
}
最后
- 我選擇獲取圖片base64字符串,主要是方便存儲和上傳.可以把字符串存在Storage中,可以同時上傳多張.
- base64字符串大小和圖片實際大小相差不大,所以不要誤解上傳base64字符串會比上傳圖片快
最后的最后
有人一直問拍照和從相冊選擇的照片如何上傳,我上面已經(jīng)說了,拍照和從相冊選擇照片返回的是base64字符串,上傳字符串我們都會吧
還不會?this.http.post('后臺接口地址', {'參數(shù)名':照片字符串}).map((res: Response) => res.json());
如果你插件獲取的圖片的絕對路徑.也可以通過以下代碼轉(zhuǎn)換為base64字符串.需要安裝File插件
/**
* 根據(jù)圖片絕對路徑轉(zhuǎn)化為base64字符串
* @param url 絕對路徑
* @param callback 回調(diào)函數(shù)
*/
convertImgToBase64(url, callback) {
this.getFileContentAsBase64(url, function (base64Image) {
callback.call(this, base64Image.substring(base64Image.indexOf(';base64,') + 8));
})
}
private getFileContentAsBase64(path, callback) {
function fail(err) {
console.log('Cannot found requested file' + err);
}
function gotFile(fileEntry) {
fileEntry.file(function (file) {
let reader = new FileReader();
reader.onloadend = function (e) {
let content = this.result;
callback(content);
};
reader.readAsDataURL(file);
});
}
this.file.resolveLocalFilesystemUrl(path).then(fileEnter => gotFile(fileEnter)).catch(err => fail(err));
// window['resolveLocalFileSystemURL'](path, gotFile, fail);
}
- 上傳到后臺后需要把字符串轉(zhuǎn)換成照片的,我這里貼出java代碼
/**
* base64字節(jié)生成圖片
*
* @param base64字符串
* @param imgFilePath 生成的圖片絕對路徑+文件名
* @return
*/
public static boolean makePicture(String base64, String imgFilePath) {
if (base64 == null) {
return false;
}
BASE64Decoder decoder = new BASE64Decoder();
try {
// Base64解碼
byte[] bytes = decoder.decodeBuffer(base64);
for (int i = 0; i < bytes.length; ++i) {
if (bytes[i] < 0) {// 調(diào)整異常數(shù)據(jù)
bytes[i] += 256;
}
}
// 生成jpeg圖片
OutputStream out = new FileOutputStream(imgFilePath);
out.write(bytes);
out.flush();
out.close();
return true;
} catch (Exception e) {
return false;
}
}