1、安装ionic native插件
git地址: https://github.com/apache/cordova-plugin-camera
$ ionic cordova plugin add cordova-plugin-camera
$ npm install --save @ionic-native/camera
2、在app.module.ts中声明插件
import { Camera } from '@ionic-native/camera';
...
@NgModule({
...
providers: [
...
Camera
...
]
...
})
export class AppModule { }
3、使用
HTML:
<
button
ion-button
(
click
)=
'addPicture()'
>选择图片
</
button
>
TypeScript:
import
{
Camera
}
from
'@ionic-native/camera'
;
import
{
ActionSheetController
}
from
'ionic-angular'
;
@
Component
({
selector:
'page-mine'
,
templateUrl:
'mine.html'
})
export
class
MinePage
{
images
:
Array
<{
src
:
string
}>;
constructor
(
private
camera
:
Camera
,
public
actionSheetCtrl
:
ActionSheetController
,
) {
}
openCamera
():void {
var
srcType
=
this
.
camera
.
PictureSourceType
.
CAMERA
;
var
options
=
this
.
setOptions
(
srcType
);
this
.
getOptions
(
options
);
};
openPic
(){
var
srcType
=
this
.
camera
.
PictureSourceType
.
PHOTOLIBRARY
;
var
options
=
this
.
setOptions
(
srcType
);
this
.
getOptions
(
options
);
}
setOptions
(
srcType
){
const
options
:
CameraOptions
=
{
quality:
100
,
destinationType:
this
.
camera
.
DestinationType
.
DATA_URL
,
encodingType:
this
.
camera
.
EncodingType
.
JPEG
,
allowEdit:
true
,
saveToPhotoAlbum:
false
,
sourceType:srcType
,
mediaType:
this
.
camera
.
MediaType
.
PICTURE
};
return
options
;
}
getOptions
(
options
){
this
.
camera
.
getPicture
(
options
).
then
((
imageData
)
=>
{
// imageData is either a base64 encoded string or a file URI
// If it's base64:
let
base64Image
=
'data:image/jpeg;base64,'
+
imageData
;
this
.
images
.
unshift
({
src:base64Image
})
}, (
err
)
=>
{
// Handle error
});
}
addPicture
()
{
let
actionSheet
=
this
.
actionSheetCtrl
.
create
({
title:
'选择图片'
,
buttons:
[
{
text:
'拍照'
,
role:
'camera'
,
handler:
()
=>
{
this
.
openCamera
();
}
},{
text:
'相册'
,
handler:
()
=>
{
this
.
openPic
();
}
},{
text:
'Cancel'
,
role:
'cancel'
,
handler:
()
=>
{
console
.
log
(
'Cancel clicked'
);
}
}
]
});
actionSheet
.
present
();
}
}
官方文档:https://ionicframework.com/docs/native/camera/