【问题标题】:Ionic 4: Cannot display camera image to userIonic 4:无法向用户显示相机图像
【发布时间】:2021-04-29 18:56:54
【问题描述】:

我只是想让用户拍照,将其存储为数据 URI,然后显示该图像。出于某种原因,这仅显示一个 boken 图像链接,我不确定我是否理解。 selectImage() 应该允许用户选择一张图片或拍摄一张新图片,然后显示该图片。

我的看法:

<ion-row *ngIf="imageSrc">
  <ion-col class="ion-text-center">
    <img alt="cropped photo" height="500px" [src]="imageSrc" />
    <p>{{imageSrc}}</p>
  </ion-col>
</ion-row>

组件:

selectImage() : void {
    this.photo.selectImageSheet().then(() => {
      if ( typeof(this.photo.imageSource) == 'number' ) {
        this.photo.pickImage(this.photo.imageSource).then(imageURI => {
          this.global.handleResponse(imageURI)
          this.imageSrc = imageURI
        })
      }
    })
  }

照片服务:

pickImage(sourceType: number) : Promise<any> {
    return new Promise((resolve, reject) => {
      this.selectImage(sourceType).then( imageURI => {
        resolve(imageURI)
      })
    })
  }

 selectImage(srcType : number = 1) : Promise<any> {

    let options: CameraOptions = {
      quality: 100,
      sourceType: srcType,
      targetWidth: 600,
      targetHeight: 1200,
      destinationType: this.camera.DestinationType.FILE_URI,
      correctOrientation: true,
      encodingType: this.camera.EncodingType.JPEG,
      mediaType: this.camera.MediaType.PICTURE
    }

    return new Promise(resolve => {
      this.camera.getPicture(options)
        .then((imageURI) => {

          this.imageData = imageURI;

          resolve(this.imageData)
        })
        .catch(err => this.globals.handleResponse(JSON.stringify(err)))
    })
  }

文档似乎很清楚,FILE_URI 应该能够设置为src,所以我真的不确定会出现什么问题......

navigator.camera.getPicture(onSuccess, onFail, { quality: 50,
    destinationType: Camera.DestinationType.FILE_URI });

function onSuccess(imageURI) {
    var image = document.getElementById('myImage');
    image.src = imageURI;
}

function onFail(message) {
    alert('Failed because: ' + message);
}

【问题讨论】:

    标签: angular cordova ionic-framework


    【解决方案1】:

    有一种流行的方法可以解决这个问题,就是像这样转换文件:

        this.imageData = this.win.Ionic.WebView.convertFileSrc(imageURI);
    

    它适用于照片和视频。这是原始回复https://stackoverflow.com/a/55934321/10243902

    不过,我更喜欢立即将图像显示为 base64。如果您想使用它,只需安装 Base64 插件:

    ionic cordova plugin add com-badrit-base64
    npm install @ionic-native/base64
    

    在构造函数上初始化

    constructor(private base64: Base64 ){ }
    

    并像这样使用它:

          this.base64.encodeFile(imageURI).then((base64Img) => {
              this.imageData = base64Img;
            })
    

    【讨论】:

    • 这样做之后我仍然有问题。 src 保存为“ionic://localhost/_app_file_/...”。那正确吗?它应该是数据而不是 URL?
    • 路径看起来正确。它应该以任何方式工作,路径或 base64 数据。尝试使用DomSanitizer 显示图像。
    猜你喜欢
    • 1970-01-01
    • 2020-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-28
    相关资源
    最近更新 更多