我正在尝试显示从相机拍摄的图像并将其显示到 View 中。我已经在许多网站上搜索了此答案,但没有任何效果。我已经尝试过DomSanitizer,Base64甚至照片库,但是从它们返回的图像没有显示。

我的home.ts文件是

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Camera, CameraOptions } from '@ionic-native/camera';
import { DomSanitizer } from '@angular/platform-browser';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  myPhoto:any;
  image;
  constructor(public navCtrl: NavController, private camera: Camera, public DomSanitizer: DomSanitizer) {

  }

  takePhoto(){
    const options: CameraOptions = {
      quality: 100,
      targetHeight: 320,
      targetWidth: 320,
      destinationType: this.camera.DestinationType.FILE_URI,
      sourceType: this.camera.PictureSourceType.CAMERA,
      encodingType: this.camera.EncodingType.JPEG,
      mediaType: this.camera.MediaType.PICTURE
    }

    this.camera.getPicture(options).then((imageData) => {
     // imageData is either a base64 encoded string or a file URI
     // If it's base64 (DATA_URL):
     this.myPhoto = 'data:image/jpeg;base64,' + imageData;
     this.image = imageData;
     console.log(this.myPhoto);
     alert(this.myPhoto);
    }, (err) => {
     // Handle error
    });
  }
}

这是我的home.html代码
<ion-header>
  <ion-navbar>
    <ion-title>
      Ionic Blank
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <button ion-button (click)="takePhoto()" >Take Photo</button>

  <!-- <img src="{{myPhoto}}"/> -->
  <!-- <img src="{{image}}"/> -->
  <!-- <img [src]="DomSanitizer.bypassSecurityTrustUrl(myPhoto)"/> -->
  <!-- <img data-ng-src="{{myPhoto}}"/> -->
  <img src="data:image/jpeg;base64,file:///storage/sdcard0/Android/data/io.ionic.starter/cache/1533211220154.jpg"/>
</ion-content>

这里的注释代码是我尝试过但未成功。

最佳答案

我使用了文件插件及其方法readAsDataURL。对我来说很好。希望它能帮助那里的人们:)

const options: CameraOptions = {
      quality: 100,
      allowEdit: true,
      sourceType:  this.camera.PictureSourceType.CAMERA ,
      saveToPhotoAlbum: true,
      correctOrientation: true,
      encodingType: this.camera.EncodingType.JPEG,
      destinationType: this.camera.DestinationType.FILE_URI
    }

this.camera.getPicture(options).then((imageData) => {

    //imageData will hold the full file path so we need to extract filename and path using file plugin
     var filename = imageData.substring(imageData.lastIndexOf('/')+1);
     var path =  imageData.substring(0,imageData.lastIndexOf('/')+1);
    //then use it in the readAsDataURL method of cordova file plugin
    //this.file is declared in constructor file :File
         this.file.readAsDataURL(path, filename).then(res=>{
           item.pic = res;
         });
}, (err) => {
 alert(err);
});

link for ionic cordova file plugin

关于ionic-framework - 无法显示来自ION框架的FILE URI的图像,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51706809/

10-12 07:28
查看更多