首页 > 解决方案 > 离子电容相机,生成全画质图像并显示,无需生成Base64和DataUri

问题描述

在我的 Ionic Project 中,我使用 Capacitor 在移动平台中进行部署。

为了从设备捕获图像,我使用的是电容相机,它可以帮助我以三种格式获取图像。1.Base64。2. 数据网址。3.文件Uri。

onCaptureImage() {
    if (!Capacitor.isPluginAvailable('Camera')) {
      this._sharedService.showToastMessage(
        'Unable To Open Camera', 1000);
      return;
    }
    Plugins.Camera.getPhoto({
      quality: 60,
      source: CameraSource.Prompt,
      correctOrientation: true,
      resultType: CameraResultType.DataUrl
    })
      .then(image => {
        const blobImg = this._sharedService.dataURItoBlob(image.dataUrl);
        this.myfiles.push(blobImg);
        this.urls.push(this.sanitizer.bypassSecurityTrustUrl(image.dataUrl));
      })
      .catch(error => {
        return false;
      });
  }

从这里DataUrl我用来显示图像并上传此图像,我将其转换为Blob然后通过FormData.

现在质量是 60,我希望质量为 100。但是当我们生成DataUrl100 质量图像时,它会挂起设备。

我只是想知道有什么方法可以生成FileUri质量为 100 的图像,并且还可以在不生成Base64或不生成图像的情况下预览图像DataUrl

谢谢。

标签: angularionic-frameworkionic4capacitor

解决方案


巨大的 base64 字符串的大小是挂起应用程序的原因。看看这个解决方案...

使用相机设置如下:

Camera.getPhoto({
    quality: 100,
    resultType: CameraResultType.Uri,
    source: CameraSource.Prompt
  }).then((image) => {
//imgSrc is passed to src of img tag
imgSrc = this.domSanitizer.bypassSecurityTrustResourceUrl(image && (image.webPath));

// image.path is what you will have to send to the uploadPhoto method as uripath
      });

Uri 格式将为您提供可以轻松传递给文件传输插件的本地文件路径... image.path是相机返回的本地文件路径..

要将文件传输到服务器,您将需要 cordova 文件传输插件..代码将如下所示..

import { FileTransfer, FileUploadOptions, FileTransferObject } from '@ionic-native/file-transfer/ngx';

constructor(private transfer: FileTransfer)

uploadPhoto(fileName:string, uripath:string):Promise<any>{
return new Promise((resolve,reject) => {
  const fileTransfer: FileTransferObject = this.transfer.create();
  const options: FileUploadOptions = {
    fileKey: 'file',
    fileName: fileName,
    mimeType: 'image/jpg',
    chunkedMode: false,
    params: {
      //any params that you want to attach for the server to use
    },
    headers: {
      //any specific headers go here
    }
  };
  fileTransfer.upload(uripath, <APIEndpointURL>, options)
    .then((result) => {
      // success
    resolve(result);
    }, (err) => {
      // error
      reject(err);
    });
});
}

有了这个,你的服务器肯定会收到文件,不管图像质量如何。我在 node.js 和 php 服务器上都使用过这个方法。


推荐阅读