ionic2/3实战-添加拍照功能cordova-plugin-camera

效果演示

源代码已上传到github

由于ionic版本更新较快,有些写法可能改变来不及更新简书,请以github代码为准
ionic2.0插件的使用方式和ionic3.0已不一样

ionic2实战-添加拍照功能cordova-plugin-camera.gif

安装插件

  • 安装cordova-plugin-camera插件,安装过程如下图
  • 我在第一次执行ionic platfrom add android时抛出了一个异常,解决了,异常详情看这里
  • 当执行ionic platfrom add android,没有问题时,说明我们的环境没有问题啦.然后在写代码.
    安装cordova-plugin-camera

封装拍照插件

  • 第一步我在src根目录新建一个providers文件夹,在这个文件夹新建一个NativeService.ts文件,叫NativeService是因为这个ts专门写app所有插件相关的代码,不止只有拍照插件
  • 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) {
      }

      /**
       * 统一调用此方法显示提示信息
       * @param message 信息内容
       * @param duration 显示时长
       */
      showToast = (message: string = '操作完成', duration: number = 2500) => {
        this.toast = this.toastCtrl.create({
          message: message,
          duration: duration,
          position: 'top',
          showCloseButton: true,
          closeButtonText: '关闭'
        });
        this.toast.present();
      };

      /**
       * 关闭信息提示框
       */
      hideToast = () => {
        this.toast.dismissAll()
      };

      /**
       * 统一调用此方法显示loading
       * @param content 显示的内容
       */
      showLoading = (content: string = '') => {
        this.loading = this.loadingCtrl.create({
          content: content
        });
        this.loading.present();
        setTimeout(() => {//最长显示20秒
          this.loading.dismiss();
        }, 20000);
      };

      /**
       * 关闭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,//保存的图像质量,范围为0 - 100
            allowEdit: true,//选择图片前是否允许编辑
            encodingType: Camera.EncodingType.JPEG,
            targetWidth: 800,//缩放图像的宽度(像素)
            targetHeight: 800,//缩放图像的高度(像素)
            saveToPhotoAlbum: false,//是否保存到相册
            correctOrientation: true//设置摄像机拍摄的图像是否为正确的方向
          }, options)).then((imageData) => {
            resolve(imageData);
          }, (err) => {
            console.log(err);
            err == 20 ? this.showToast('没有权限,请在设置中开启权限') : 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中,如下图
    Paste_Image.png

使用

我的html页面代码

    <ion-header>
      <ion-toolbar>
        <ion-title>
          设置个人头像
        </ion-title>
        <ion-buttons start>
          <button ion-button (click)="dismiss()">
            <span showWhen="ios">关闭</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;//头像是否改变标识
      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);//这是头像数据.
          this.nativeService.showLoading('正在上传....');
          this.viewCtrl.dismiss({avatarPath: this.avatarPath});//这里可以把头像传出去.
        } else {
          this.dismiss();
        }
      }

      dismiss() {
        this.viewCtrl.dismiss();
      }
    }

最后

  • 我选择获取图片base64字符串,主要是方便存储和上传.可以把字符串存在Storage中,可以同时上传多张.
  • base64字符串大小和图片实际大小相差不大,所以不要误解上传base64字符串会比上传图片快

最后的最后

  • 有人一直问拍照和从相册选择的照片如何上传,我上面已经说了,拍照和从相册选择照片返回的是base64字符串,上传字符串我们都会吧
    还不会?this.http.post('后台接口地址', {'参数名':照片字符串}).map((res: Response) => res.json());

  • 如果你插件获取的图片的绝对路径.也可以通过以下代码转换为base64字符串.需要安装File插件

 /**
   * 根据图片绝对路径转化为base64字符串
   * @param url 绝对路径
   * @param callback 回调函数
   */
  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);
  }
  • 上传到后台后需要把字符串转换成照片的,我这里贴出java代码
 /**
     * base64字节生成图片
     *
     * @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) {// 调整异常数据
                    bytes[i] += 256;
                }
            }
            // 生成jpeg图片
            OutputStream out = new FileOutputStream(imgFilePath);
            out.write(bytes);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            return false;
        }
    }

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 157,298评论 4 360
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,701评论 1 290
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 107,078评论 0 237
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,687评论 0 202
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,018评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,410评论 1 211
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,729评论 2 310
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,412评论 0 194
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,124评论 1 239
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,379评论 2 242
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,903评论 1 257
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,268评论 2 251
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,894评论 3 233
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,014评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,770评论 0 192
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,435评论 2 269
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,312评论 2 260

推荐阅读更多精彩内容