How to convert Camera Image to blob in ionic 5?

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

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

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

If you’re getting the base64 string, you can use a reference point from this stackoverflow post here.

Here is the quick and easy way to convert data url to file.

 dataURLtoFile(dataurl, filename) {
        let arr = dataurl.split(','),
            mime = arr[0].match(/:(.*?);/)[1],
            bstr = atob(arr[1]),
            n = bstr.length,
            u8arr = new Uint8Array(n);
        while (n--) {
            u8arr[n] = bstr.charCodeAt(n);
        }
        return new File([u8arr], filename, {type: mime});
    }
,,,,,,,,,,,,
,,,,,,,,,,,
,,,,,,,,,,
,,,,,,,,,
,,,,,,,,
,,,,,,,
,,,,,,
,,,,,
,,,,
,,,
,,
,
someFunction() {
  this.signature = this.dataURLtoFile('dataUrlHere', 'fileName.png');`
  const fd = new FormData();
  fd.append('file', this.signature);
   this.httpClient.post('url', fd).subscribe(res => {
        console.log(res)
    });
}
1 Like