且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在ionic 5中将“相机图像"转换为blob?

更新时间:2022-01-02 22:04:40

要获取Blob,您需要做一些事情:

In order to obtain the blob you need a few things:

首先,确保将Camera插件的选项设置为返回FILE_URI(URL到图像的二进制文件):

First, make sure that the options of Camera plugin are set to return FILE_URI (URL to the binary file of the image):

  options: CameraOptions = {
    quality: 100,
    destinationType: this.camera.DestinationType.FILE_URI, // set to FILE_URI
    encodingType: this.camera.EncodingType.JPEG,
    mediaType: this.camera.MediaType.PICTURE
  };

第二,由于FILE_URI只是一个链接而不是实际文件,因此您需要一种获取它的方法.您可以使用文件插件来做到这一点:

Second, since FILE_URI is just a link and not actual file, you need a way to obtain it. You can do that using File plugin:

// Import it:

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

// Then use it in the method that Camera plugin has for taking pictures:

  getPicture() {
    this.camera.getPicture(this.options).then((imageDataURI) => {
      this.file.resolveLocalFilesystemUrl(imageDataURI).then((entry: FileEntry) => 
      {
        entry.file(file => {
          console.log(file);
          this.readFile(file);
        });
      });
    }, (err) => {
      // Handle error
    });
  };

最后将其发送到您的服务器,您需要读取文件:

Lastly to send it to your server, you need to read the file:

  read(file) {
    const reader = new FileReader();
    reader.onload = () => {
      const blob = new Blob([reader.result], {
        type: file.type
      });
      const formData = new FormData();
      formData.append('name', 'MyImageBlob');
      formData.append('file', blob, file.name);
      this.service.upload(formData).subscribe(response => {
        console.log(response);
      });
    };
    reader.readAsArrayBuffer(file);
  };

让我知道您是否可以从这里拿走它.

Let me know if you can take it from here.