cordova - 应用程序中来自相机和图库的离子显示图像
问题描述
我正在尝试使用相机 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));
}
}
问题是图像未显示在我的视图中,并在其位置出现损坏的图像图标,如下所示。我见过的所有示例都使用类似的代码,并且它们都存在图像链接损坏的问题,而不是显示的实际图像。
解决方案
您可以使用@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) => {
});
推荐阅读
- reactjs - 如何通过reactjs中的http请求发送函数
- xamarin - 使用模态页面处理滑动
- c# - .NET Core 3.1 - 范围服务 - 事件处理程序多次调用
- java - RemoteWeb Driver 驱动程序未初始化,因为未找到参数值
- linux - 使用 netcat 命令无法正确检查打开的端口
- java - 在列表中查找特定对象的最有效方法
- oracle - 使用表名参数化的存储过程禁用/启用 Oracle 表中的约束
- forms - 您在连接字符串中指定了密码,但您使用的本机 SQLite 库不支持加密
- image-processing - 使用许多训练数据进行模型不学习
- sql - 如何知道 Oracle SQL 中当前登录的用户名?