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

use*_*454 2 ionic-framework

我想发布多部分表单数据,为此,我们可以这样做:

\n\n
let formData = new FormData()\nformData.append(\'myfile\', \'your blob\')\n\nthis.http.post(url, formData)\n
Run Code Online (Sandbox Code Playgroud)\n\n

但我不知道如何将相机图像转换为斑点。我正在使用本机相机插件,这里是我的代码:

\n\n
  cameraOptions: CameraOptions = {\n    quality: 20,\n    destinationType: this.camera.DestinationType.DATA_URL,\n    encodingType: this.camera.EncodingType.JPEG,\n    mediaType: this.camera.MediaType.PICTURE,\n    sourceType: this.camera.PictureSourceType.PHOTOLIBRARY\n  }\n\nconstructor(public camera: Camera){}\n\ntakePhoto() {\n    return new Promise(resolve => {\n      this.camera.getPicture(this.cameraOptions).then((imageData) => {\n        resolve(imageData);\n      }, (err) => {\n        resolve(err);\n      });\n    });\n  }\n
Run Code Online (Sandbox Code Playgroud)\n\n

我为 blob 尝试了以下代码:

\n\n
dataURLtoBlob(dataURL) {\n    debugger;\n    // convert base64/URLEncoded data component to raw binary data held in a string\n    let byteString: string;\n    if (dataURL.split(\',\')[0].indexOf(\'base64\') >= 0) {\n      byteString = atob(dataURL.split(\',\')[1]);\n    } else {\n      byteString = unescape(dataURL.split(\',\')[1]);\n    }\n    // separate out the mime component\n    let mimeString = dataURL\n      .split(\',\')[0]\n      .split(\':\')[1]\n      .split(\';\')[0];\n\n    // write the bytes of the string to a typed array\n    let ia = new Uint8Array(byteString.length);\n    for (let i = 0; i < byteString.length; i++) {\n      ia[i] = byteString.charCodeAt(i);\n    }\n\n    let blobImg = new Blob([ia], { type: mimeString });\n    console.log(blobImg);\n    this.blobImage = blobImg;\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

使用此代码,我能够获取图像数据,但如何在 blob 中进行转换,\n请帮助...

\n\n

你好@sergey-rudenko 这是我的输出

\n\n

获取图片输出:

\n\n
imageDataURI:  content://com.android.providers.media.documents/document/image%3A78702\n
Run Code Online (Sandbox Code Playgroud)\n\n

this.file.resolveLocalFilesystemUrl 输出:

\n\n
entry:  \n\nFileEntry {isFile: true, isDirectory: false, name: "image:78702", fullPath: "/com.android.providers.media.documents/document/image:78702", filesystem: FileSystem, \xe2\x80\xa6}\nfilesystem: FileSystem {name: "content", root: DirectoryEntry}\nfullPath: "/com.android.providers.media.documents/document/image:78702"\nisDirectory: false\nisFile: true\nname: "image:78702"\nnativeURL: "content://com.android.providers.media.documents/document/image%3A78702"\n__proto__: Entry\n
Run Code Online (Sandbox Code Playgroud)\n\n

条目.文件输出:

\n\n
file:  \nFile {name: "content", localURL: "cdvfile://localhost/content/com.android.providers.media.documents/document/image%3A78702", type: "image/jpeg", lastModified: 1588099237000, lastModifiedDate: 1588099237000, \xe2\x80\xa6}\nend: 79807\nlastModified: 1588099237000\nlastModifiedDate: 1588099237000\nlocalURL: "cdvfile://localhost/content/com.android.providers.media.documents/document/image%3A78702"\nname: "content"\nsize: 79807\nstart: 0\ntype: "image/jpeg"\n__proto__: Object\n
Run Code Online (Sandbox Code Playgroud)\n\n

常量 blob 输出:

\n\n
Blob {size: 79807, type: "image/jpeg"}\nsize: 79807\ntype: "image/jpeg"\n__proto__: Blob\n
Run Code Online (Sandbox Code Playgroud)\n\n

表单数据输出:

\n\n
FormData {}\n__proto__: FormData\nappend: \xc6\x92 append()\n  arguments: (...)\n  caller: (...)\n  length: 2\n  name: "append"\n  __proto__: \xc6\x92 ()\n  [[Scopes]]: Scopes[0]\ndelete: \xc6\x92 delete()\nentries: \xc6\x92 entries()\nforEach: \xc6\x92 forEach()\nget: \xc6\x92 ()\ngetAll: \xc6\x92 getAll()\nhas: \xc6\x92 has()\nkeys: \xc6\x92 keys()\nset: \xc6\x92 ()\nvalues: \xc6\x92 values()\nconstructor: \xc6\x92 FormData()\nSymbol(Symbol.iterator): \xc6\x92 entries()\nSymbol(Symbol.toStringTag): "FormData"\n__proto__: Object\n
Run Code Online (Sandbox Code Playgroud)\n

Ser*_*nko 6

为了获得 blob,你需要一些东西:

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

options: CameraOptions = {
  quality: 100,
  destinationType: this.camera.DestinationType.FILE_URI, // set to FILE_URI
  encodingType: this.camera.EncodingType.JPEG,
  mediaType: this.camera.MediaType.PICTURE
};
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

如果您可以从这里拿走它,请告诉我。