从 Ionic 2 的照片库中选择照片时不显示照片



我正在使用Ionic 2中的相机插件上传照片。我正在安卓设备上运行该应用程序。Carema 捕获显示在应用程序中,但从图库中选择照片时,不会显示照片。

以下方法用于相机和画廊:

private openCamera(){
var options: CameraOptions = {
sourceType: this.camera.PictureSourceType.CAMERA,
destinationType: this.camera.DestinationType.DATA_URL,
allowEdit: true,
saveToPhotoAlbum: true
};
this.camera.getPicture(options).then((imageData) => {
this.cameraData = 'data:image/jpeg;base64,' + imageData;
this.photoTaken = true;
this.photoSelected = false;
let base64Image = 'data:image/jpeg;base64,' + imageData;
}, (err) => {
// Handle error
});
}
private selectFromGallery() {
var options = {
sourceType: this.camera.PictureSourceType.PHOTOLIBRARY,
destinationType: this.camera.DestinationType.FILE_URI
};
this.camera.getPicture(options).then((imageData) => {
this.cameraUrl = imageData;
this.photoSelected = true;
this.photoTaken = false;
}, (err) => {
// Handle error
});
}

以下是要在 HTML 页面中显示的代码:

<img [src]="cameraData" *ngIf="photoTaken">
<img [src]="cameraUrl" *ngIf="photoSelected">

当您从库中选择时,您需要使用文件插件来获取本地文件系统 url。

要安装:

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

进口:

import { File } from '@ionic-native/file';

在您的代码中:

constructor( private file: File, .... ) {}
.....

const options: CameraOptions = {
destinationType: this.camera.DestinationType.FILE_URI,
sourceType: this.camera.PictureSourceType.PHOTOLIBRARY
}
this.camera.getPicture(options).then((imageURI) => {
this.file.resolveLocalFilesystemUrl(imageURI).then(fileEntry => {
this.cameraUrl = fileEntry.nativeURL;
this.photoSelected = true;
this.photoTaken = false;
});
}, (err) => {
// Handle error
});

编辑

您可能需要清理 img src 的值:

<img *ngIf="cameraUrl" [src]="sanitizeUrl(cameraUrl)"   />

该函数:

import { DomSanitizer } from '@angular/platform-browser';
....
constructor( private sanitizer: DomSanitizer, .... ) {}
....
sanitizeUrl(url) {
return this.sanitizer.bypassSecurityTrustUrl(url);
}

最新更新