离子电容相机,生成全质量图像并显示,无需生成 Base64 和 DataUri

Yas*_*ain 2 ionic-framework angular ionic4 capacitor

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

为了从设备捕获图像,我使用了 Capacitor Camera,它可以帮助我以三种格式获取图像。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;
      });
  }
Run Code Online (Sandbox Code Playgroud)

从这个DataUrl我用来显示图像和上传这个图像,我将它转换成Blob然后通过FormData.

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

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

谢谢。

Che*_*sal 6

巨大的 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
      });
Run Code Online (Sandbox Code Playgroud)

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);
    });
});
}
Run Code Online (Sandbox Code Playgroud)

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