Cordova 的插件机制一直是使用Ionic App的特色,即插即用的特性也使cordova 的插件变的更轻便和灵活
App 开发中,相机的调用以及相册的调用是比较常见的需求,采用Ionic 开发Hybrid App 时,可以通过使用Ionic native cameraIonic native camera插件。
安装插件
ionic cordova plugin add cordova-plugin-camera
npm install @ionic-native/camera
-
iOS 设置
ios10以上版本,需要在工程目录的info.plist 添加获取权限的字符描述,如果不添加,App调起相机时会crash, 配置如下图:
对应的中英文翻译:
同样可以在comfig.xml中设置标签来添加权限的字符描述:
<edit-config target="NSCameraUsageDescription" file="*-Info.plist" mode="merge">
<string>need camera access to take pictures</string>
</edit-config>
<edit-config target="NSPhotoLibraryUsageDescription" file="*-Info.plist" mode="merge">
<string>need photo library access to get pictures from there</string>
</edit-config>
<edit-config target="NSLocationWhenInUseUsageDescription" file="*-Info.plist" mode="merge">
<string>need location access to find things nearby</string>
</edit-config>
<edit-config target="NSPhotoLibraryAddUsageDescription" file="*-Info.plist" mode="merge">
<string>need photo library access to save pictures there</string>
</edit-config>
- Android 设置
android7 以后调用相机需要设置相关权限,在AndroidMainfest.xml中添加如下:
<uses-permission android:name="android.permission.INTERNET" />
<!-- Camera, Photos, input file -->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
插件使用
插件相关Api: https://github.com/apache/cordova-plugin-camera
使用相机的问题总结:
- 设置调用相机返回图片地址为Camera.DestinationType = 1( FILE_URI),返回的图片路径,Img 标签无法读取。
解决方法:
ionic 3 需要调用window.Ionic.normalizeURL()
ionic 4 window.Ionic.WebView.convertFileSrc()
如果在读取图片时,浏览器由于安全问题拒绝访问,即在控制台中报错” unsafe:://capacitor:xxxx“,则需要在convertFileSrc之后
import { DomSanitizer } from '@angular/platform-browser';
constructor( private sanitizer: DomSanitizer){}
...
this.sanitizer.bypassSecurityTrustUrl( src )
拍照后照片横屏:
option = {
...
correctOrientation: true
}拍照的图片size过大:
option = {
...
quality: 30( 0 - 100)
}拍照后的图片上传至云端
option = {
....
destinationType: this.camera.DestinationType.FILE_URI
}
同时使用# cordova-plugin-advanced-http
cordova.plugin.http.uploadFile(
url,
{id: '1', message: 'img'},
{ Authorization: 'OAuth2: token', FromData: 'file'},
filePath,
'file',
() => {
});
}, () => {
});
}
);