【问题标题】:How to convert Camera Image to blob in ionic 5?如何将相机图像转换为离子 5 中的斑点?
【发布时间】:2021-09-25 10:17:08
【问题描述】:

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

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

this.http.post(url, formData)

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

  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 尝试了这段代码:

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, 请帮忙...

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

获取图片输出:

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

this.file.resolveLocalFilesystemUrl 输出:

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 输出:

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

常量 blob 输出:

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

formData 输出:

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

【问题讨论】:

    标签: ionic-framework


    【解决方案1】:

    为了获得 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
    };
    

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

    // 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
      });
    };
    

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

    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);
    };
    

    如果你能从这里拿走,请告诉我。

    【讨论】:

    • 请查看我的问题,我添加了您的答案的输出
    • 很酷,还有什么不工作?好像你得到了blob吗?你能澄清剩下的问题吗?
    • 没问题,但我不知道它看起来如何,我的意思是 blob,所以为了确认,我添加了输出
    • 啊,我明白了;)所以是的,blob 在控制台中不会“可见”,但您的日志输出确认它存在。
    • 我使用的是 ionic 5,但是 this.file.resolveLocalFilesystemUrl(imageDataURI).then((entry: FileEntry) 返回一个 Entry 对象而不是 FileEntry。因此下面的代码不起作用。为什么可以那是?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-17
    • 1970-01-01
    • 2012-12-02
    • 2019-12-12
    • 2014-11-03
    • 2018-09-29
    相关资源
    最近更新 更多