如何在ionic 5中将“相机图像"转换为blob? [英] How to convert Camera Image to blob in ionic 5?

查看:276
本文介绍了如何在ionic 5中将“相机图像"转换为blob?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to post multipart form data, for this, we can do like this:

let formData = new FormData()
formData.append('myfile', 'your blob')

this.http.post(url, formData)

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

But I don't know how to convert a camera image to the blob. I am using native camera plugin and here my code:

  cameraOptions: CameraOptions = {
    quality: 20,
    destinationType: this.camera.DestinationType.DATA_URL,
    encodingType: this.camera.EncodingType.JPEG,
    mediaType: this.camera.MediaType.PICTURE,
    sourceType: this.camera.PictureSourceType.PHOTOLIBRARY
  }

constructor(public camera: Camera){}

takePhoto() {
    return new Promise(resolve => {
      this.camera.getPicture(this.cameraOptions).then((imageData) => {
        resolve(imageData);
      }, (err) => {
        resolve(err);
      });
    });
  }

我为blob尝试了以下代码:

I tried this code for blob:

dataURLtoBlob(dataURL) {
    debugger;
    // convert base64/URLEncoded data component to raw binary data held in a string
    let byteString: string;
    if (dataURL.split(',')[0].indexOf('base64') >= 0) {
      byteString = atob(dataURL.split(',')[1]);
    } else {
      byteString = unescape(dataURL.split(',')[1]);
    }
    // separate out the mime component
    let mimeString = dataURL
      .split(',')[0]
      .split(':')[1]
      .split(';')[0];

    // write the bytes of the string to a typed array
    let ia = new Uint8Array(byteString.length);
    for (let i = 0; i < byteString.length; i++) {
      ia[i] = byteString.charCodeAt(i);
    }

    let blobImg = new Blob([ia], { type: mimeString });
    console.log(blobImg);
    this.blobImage = blobImg;
}

使用此代码,我可以获取图像数据,但如何在Blob中进行转换, 请帮忙...

With this code, I am able to get image data but how to convert in a blob, please help...

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

Hello @sergey-rudenko here my output

getPicture输出:

getPicture output:

imageDataURI:  content://com.android.providers.media.documents/document/image%3A78702

this.file.resolveLocalFilesystemUrl输出:

this.file.resolveLocalFilesystemUrl output:

entry:  

FileEntry {isFile: true, isDirectory: false, name: "image:78702", fullPath: "/com.android.providers.media.documents/document/image:78702", filesystem: FileSystem, …}
filesystem: FileSystem {name: "content", root: DirectoryEntry}
fullPath: "/com.android.providers.media.documents/document/image:78702"
isDirectory: false
isFile: true
name: "image:78702"
nativeURL: "content://com.android.providers.media.documents/document/image%3A78702"
__proto__: Entry

entry.file输出:

entry.file output:

file:  
File {name: "content", localURL: "cdvfile://localhost/content/com.android.providers.media.documents/document/image%3A78702", type: "image/jpeg", lastModified: 1588099237000, lastModifiedDate: 1588099237000, …}
end: 79807
lastModified: 1588099237000
lastModifiedDate: 1588099237000
localURL: "cdvfile://localhost/content/com.android.providers.media.documents/document/image%3A78702"
name: "content"
size: 79807
start: 0
type: "image/jpeg"
__proto__: Object

const blob输出:

const blob output:

Blob {size: 79807, type: "image/jpeg"}
size: 79807
type: "image/jpeg"
__proto__: Blob

formData输出:

formData output:

FormData {}
__proto__: FormData
append: ƒ append()
  arguments: (...)
  caller: (...)
  length: 2
  name: "append"
  __proto__: ƒ ()
  [[Scopes]]: Scopes[0]
delete: ƒ delete()
entries: ƒ entries()
forEach: ƒ forEach()
get: ƒ ()
getAll: ƒ getAll()
has: ƒ has()
keys: ƒ keys()
set: ƒ ()
values: ƒ values()
constructor: ƒ FormData()
Symbol(Symbol.iterator): ƒ entries()
Symbol(Symbol.toStringTag): "FormData"
__proto__: Object

推荐答案

要获取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.

这篇关于如何在ionic 5中将“相机图像"转换为blob?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆