我们想在应用程序内部安装一台录像机,而无需打开手机的原生录像机,就像Snapchat用于视频录制一样

时间:2018-06-06 13:03:44

标签: ionic-framework

我们遇到相机图像问题,当我们点击相机预览中的图像时,它会拍摄比相机预览尺寸更大的图像。我们希望相机预览和图像点击大小相同。我们正在使用带有相机预览插件的离子3

我们想在应用程序内部安装一台录像机,而无需打开手机的原生录像机,就像Snapchat用于视频录制一样

以下是我们所做的代码

import { Component, ViewChild } from "@angular/core";
import { IonicPage, App, Content, NavController, Platform, ViewController, NavParams } from "ionic-angular";
// import {CameraPreview} from "@ionic-native/camera-preview";
import { CameraPreview, CameraPreviewPictureOptions, CameraPreviewOptions, CameraPreviewDimensions } from '@ionic-native/camera-preview';
import { Camera, CameraOptions } from '@ionic-native/camera';
import { Base64 } from '@ionic-native/base64';


import { TabsService } from "../../util/tabservice";
import { ShowPhotoPage } from '../show-photo/show-photo';
import { PhotoLibrary } from "@ionic-native/photo-library";
import { UnsplashItUtil } from "../../util/unsplashItutil";
import { ImageService } from "../../util/imageservice";
import { ImageEntity } from "../../util/ImageEntity";
import { Base64ToGallery } from "@ionic-native/base64-to-gallery";
import { NativeStorage } from "@ionic-native/native-storage";
import { HomePage } from "../home/home";
import { MediaCapture, MediaFile, CaptureError, CaptureVideoOptions } from '@ionic-native/media-capture';
import { Media, MediaObject } from '@ionic-native/media';
import { File } from '@ionic-native/file';
import { Storage } from '@ionic/storage';
import { TabsPage } from "../tabs/tabs";
const MEDIA_FILES_KEY = 'mediaFiles';
/**
 * Generated class for the ManagephotoPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-managephoto',
  templateUrl: 'managephoto.html',
})
export class ManagephotoPage {
  mediaFiles = [];
  @ViewChild('myvideo') myVideo: any;

  srcPhoto;
  segment = "photo";
  images = [];
  selectedPhoto;

  @ViewChild(Content)
  content: Content;
  frmWedInv: any;

  tabBarElement: any;

  imageURI: any;
  isImageSelected: boolean = false;

  wedNam: any;
  wedTheme: any;

  constructor(public navParams: NavParams, public viewCtrl: ViewController, public navCtrl: NavController, private storage: Storage,
    public cameraPreview: CameraPreview,
    public platform: Platform,
    public tabsService: TabsService,
    private photoLibrary: PhotoLibrary,
    private imageService: ImageService,
    private viewController: ViewController, private media: Media,
    private app: App, public unsplash: UnsplashItUtil,
    private mediaCapture: MediaCapture, private file: File,
    private camera: Camera, private base64: Base64, public nativeStorage: NativeStorage) {
    let self = this;

    this.tabBarElement = document.querySelector('#tabs .tabbar.show-tabbar');
    this.tabBarElement.style.display = 'none';

    this.nativeStorage.getItem('themeImg').then((s) => {
      this.wedNam = s.property1;
      this.wedTheme = s.property2;
    }
    ).catch(ex => {

    });

    this.frmWedInv = this.navParams.get("frmWedInv");
    console.log("visited camera");
  }

  chooseFile() {
    console.log('gdf');
    let options: CameraOptions = {
      quality: 100,
      destinationType: this.camera.DestinationType.DATA_URL,
      sourceType: this.camera.PictureSourceType.PHOTOLIBRARY,
      allowEdit: true,
      encodingType: this.camera.EncodingType.JPEG,
      targetWidth: 1280,
      targetHeight: 1280,
      saveToPhotoAlbum: false
    };


    this.camera.getPicture(options).then((img) => {
      // this.imageURI = img;
      this.imageURI = "data:image/jpeg;base64," + img;
      this.navCtrl.push(ShowPhotoPage, { photo: this.imageURI });
      // this.base64.encodeFile(filePath).then((base64File: string) => {

      // }, (err) => {
      //   console.log(err);
      // });

    }).catch((reason) => {
      console.log(reason);
    });
  }


  backLnk() {
    this.navCtrl.parent.select(0);
  }
  back1() {
    this.stopCamera();
    this.navCtrl.pop();
    //this.navCtrl.setRoot(HomePage);
  }

  flashMode = "off";

  changeSegment(value) {
    this.segment = value;

    if (value == "photo" || value == 'video') {
      this.startCamera();
    } else {
      this.stopCamera();
    }
  }

  flash() {
    console.log(this.flashMode)
    if (this.flashMode == 'off') {
      this.flashMode = 'on'
    }
    else if (this.flashMode == 'on') {
      this.flashMode = 'auto'
    } else {
      this.flashMode = 'off'
    }

    this.setFlashMode();

  }

  setFlashMode() {
    this.cameraPreview.setFlashMode(this.flashMode).then(() => {

    }).catch(() => {

    });
  }

  takePicture() {
    let self = this;
    var number = window.innerHeight / 5;
    const pictureOpts = {
      quality: 80,
      width: 1280,
      height: 400,
      // width: this.platform.width(),
      // height: this.platform.height() / 1.9,
      // targetWidth:this.platform.width(),
      // targetHeight:this.platform.height() / 1.9,
      // correctOrientation: true,
      // encodingType:this.camera.EncodingType.JPEG,
    };
this.cameraPreview.getSupportedPictureSizes().then(data=>{
  data.forEach(element => {
    console.log(JSON.stringify(element));
  });
})


    this.cameraPreview.takePicture(pictureOpts).then(base64PictureData => {
      //   console.log("aqui takando foto", base64PictureData)
      alert(JSON.stringify(pictureOpts));
      self.srcPhoto = "data:image/jpeg;base64," + base64PictureData;
      console.log(this.navParams.get("topCamera") + " oooooooooooo")
      this.navCtrl.push(ShowPhotoPage, { photo: self.srcPhoto, topCamera1: this.navParams.get("topCamera") });
      // const index = this.viewCtrl.index;
      // this.navCtrl.remove(index);
      self.cameraPreview.hide().then(() => {

      })

    });
  }


  ionViewWillEnter() {
    this.tabBarElement = document.querySelector('#tabs .tabbar.show-tabbar');
    this.tabBarElement.style.display = 'none';

    setTimeout(() => {
      this.unsplash.getListOfImages(100).then(list => {
        this.images = list;
        this.selectedPhoto = this.images[0].mediumSizeUrl;
      })
      //console.log(JSON.stringify(this.images));

      // this.images =Array( this.imageService.getImages());


    }, 300);

    if (this.segment == 'photo') {
      this.startCamera();
    }

  }

  goToPhoto() {

    this.navCtrl.push(ShowPhotoPage, { photo: this.selectedPhoto });
  }

  changePhoto(newImage) {

    this.selectedPhoto = newImage.mediumSizeUrl;
    this.content.scrollToTop(300);

  }


  back() {
    // alert();
    this.stopCamera();
    // this.navCtrl.pop();
    // this.app.getRootNav().getActiveChildNav().select(0);
    // this.navCtrl.parent.select(0);
    this.navCtrl.setRoot(TabsPage);
    // try {
    //   this.app.getRootNav().getActiveChildNav().select(0);
    //   // this.viewController.dismiss();
    // } catch (e) {

    // }

  }

  stopCamera() {
    try {
      this.cameraPreview.stopCamera().catch(e => {

      });
    } catch (e) {
      console.log(JSON.stringify(e));
    }
  }

  getPosition() {
    return (this.platform.height() / 1.9) - 20
  }

  getHeight() {
    return this.platform.height() - this.getPosition() - 64;
  }

  cmrBtnPos() {
    return (this.platform.height() / 1.9) + 100;
  }

  glryBtnPos() {
    return (this.platform.height() / 1.9) + 125;
  }

  startCamera() {


    this.stopCamera();







    this.cameraPreview.startCamera({
      x: 0,
      y: 50,
      width: this.platform.width(),
      height: this.platform.height() / 3,
      camera: 'back',
      tapPhoto: false,
      tapToFocus: true,
      previewDrag: false,
      toBack: false,

      //alpha: 0
    }).then(() => {
      console.log("camera started")
      this.setFlashMode();
    }).catch(() => {
      console.log("camera error")
    })


  }

  refresh() {
    this.cameraPreview.switchCamera();
  }

  // ionViewDidLoad() {
  //   console.log('ionViewDidLoad ManagephotoPage');
  // }

  public unregisterBackButtonAction: any;


  ionViewDidLoad() {
    console.log('ionViewDidLoad ManagephotoPage');
    this.storage.get(MEDIA_FILES_KEY).then(res => {
      this.mediaFiles = JSON.parse(res) || [];
    })
  }

  ionViewDidEnter() {
    this.tabBarElement = document.querySelector('#tabs .tabbar.show-tabbar');
    this.tabBarElement.style.display = 'none';
    this.initializeBackButtonCustomHandler();
    console.log("Enter")
  }
  ionViewWillLeave() {
    this.tabBarElement.style.display = 'flex';
    this.stopCamera();
    // Unregister the custom back button action for this page
    this.unregisterBackButtonAction && this.unregisterBackButtonAction();
  }



  initializeBackButtonCustomHandler(): void {
    this.unregisterBackButtonAction = this.platform.registerBackButtonAction(function (event) {
      console.log('Prevent Back Button Page Change');
    }, 101); // Priority 101 will override back button handling (we set in app.component.ts) as it is bigger then priority 100 configured in app.component.ts file */
  }

  captureVideo() {
    let options: CaptureVideoOptions = {
      limit: 1,
      duration: 10
    }
    this.mediaCapture.captureVideo(options).then((res: MediaFile[]) => {
      let capturedFile = res[0];
      let fileName = capturedFile.name;
      let dir = capturedFile['localURL'].split('/');
      dir.pop();
      let fromDirectory = dir.join('/');
      var toDirectory = this.file.dataDirectory;

      this.file.copyFile(fromDirectory, fileName, toDirectory, fileName).then((res) => {
        this.storeMediaFiles([{ name: fileName, size: capturedFile.size }]);
      }, err => {
        console.log('err: ', err);
      });
    },
      (err: CaptureError) => console.error(err));
  }
  storeMediaFiles(files) {
    this.storage.get(MEDIA_FILES_KEY).then(res => {
      if (res) {
        let arr = JSON.parse(res);
        arr = arr.concat(files);
        this.storage.set(MEDIA_FILES_KEY, JSON.stringify(arr));
      } else {
        this.storage.set(MEDIA_FILES_KEY, JSON.stringify(files))
      }
      this.mediaFiles = this.mediaFiles.concat(files);
    })
  }
  play(myFile) {

    if (myFile.name.indexOf('.wav') > -1) {
      const audioFile: MediaObject = this.media.create(myFile.localURL);
      audioFile.play();
    } else {
      let path = this.file.dataDirectory + myFile.name;
      let url = path.replace(/^file:\/\//, '');
      let video = this.myVideo.nativeElement;
      video.src = url;
      console.log(url);
      video.play();
    }
  }
}

0 个答案:

没有答案