Ionic 相机插件

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, 配置如下图:


    Screen Shot 2019-09-22 at 11.23.54 AM.png

    对应的中英文翻译:

Screen Shot 2019-09-22 at 11.25.02 AM.png

同样可以在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',
            () => {
             
                });
            }, () => {
               
                });
            }
        );
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 今天偶遇以前单位的小妹妹,印象中的她大大咧咧,活泼开朗,踏实努力每每想起心中总是满满的欣赏和喜悦。今天的她和...
    党海娟阅读 469评论 0 0
  • 第六个十三天,对于自己感觉是比较困难的。成为队长,首先需要做好服务,做好服务首先需要管好自己。 说实话,第六个十三...
    心我听你说阅读 214评论 0 0
  • 我难为的不是你,是我自己 南方的夏天,你想象不到的热。 你听说过夜班这个词汇吗? 在南方,这词是个噩梦。不是因为晚...
    德丽vvv阅读 296评论 0 2