首页 > 解决方案 > 应用程序中来自相机和图库的离子显示图像

问题描述

我正在尝试使用相机 Cordova 插件来显示从相机拍摄的图像或从应用程序内的设备中选取的图像。

使用这个项目作为指导 我的代码:

安装插件:

$ ionic cordova plugin add cordova-plugin-camera
$ npm install --save @ionic-native/camera@4

在 html 文件中

<ion-header>
  <ion-navbar>
    <ion-title>Hello Ionic</ion-title>
  </ion-navbar>
</ion-header>


<ion-content padding>
<h3 text-center>
  {{imageSrc}}
</h3>
<div class="gallery-button" text-center>
  <img [src]="imageSrc" />    
</div>

</ion-content>

在 ts 文件中

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

.
.
.
.

private imageSrc: string;

getImage() {
let cameraOptions = {
      sourceType: this.camera.PictureSourceType.PHOTOLIBRARY,
      destinationType: this.camera.DestinationType.FILE_URI,      
      quality: 100,
      targetWidth: 1000,
      targetHeight: 1000,
      encodingType: this.camera.EncodingType.JPEG,      
      correctOrientation: true
    }
    console.log(cameraOptions);
    this.camera.getPicture(cameraOptions)
      .then(file_uri => this.imageSrc = file_uri, 
      err => console.log(err));   
  }

}

问题是图像未显示在我的视图中,并在其位置出现损坏的图像图标,如下所示。我见过的所有示例都使用类似的代码,并且它们都存在图像链接损坏的问题,而不是显示的实际图像。

问题

标签: cordovaionic-frameworkionic2ionic3cordova-plugins

解决方案


您可以使用@ionic-native/file-path 节点模块来解析文件路径,如下所示:基本上,如果我们从照片库中选择图像,那么我们必须解析路径以获得正确的文件路径。

这是我用过的:

  // Get the data of an image
        this.camera.getPicture({
            quality: 60,
            sourceType: sourceType,
            saveToPhotoAlbum: false,
            encodingType: this.camera.EncodingType.JPEG,
            mediaType: this.camera.MediaType.PICTURE,
            correctOrientation: true  //Corrects Android orientation quirks
        }).then((imagePath: string) => {

            // Special handling for Android
            if ((this.platform.is('android') || this.platform.is('Android')) && sourceType === this.camera.PictureSourceType.PHOTOLIBRARY) {

                this.filePath.resolveNativePath(imagePath)
                    .then((filePath: string) => {

                        let correctPath: string = filePath.substr(0, filePath.lastIndexOf('/') + 1);
                        let currentName: string = filePath.substr(filePath.lastIndexOf('/') + 1);
                        console.log('currentName', currentName);
                        console.log('correctPath', correctPath);

                    }).catch((ex: string) => {

                    });

            } else {
                let currentName: string = imagePath.substr(imagePath.lastIndexOf('/') + 1);
                let correctPath: string = imagePath.substr(0, imagePath.lastIndexOf('/') + 1);

            }
        }, (error: any) => {


        });

推荐阅读