Reputation: 698
I need to convert the result from the Capacitor Camera plugin to a Blob for upload to Firebase Storage.
I could upload the Base64 string but I already upload Blobs/Files from a Browse button's FileList so I'd like not to change the design of this.
The Camera plugin provides the image data as a Base64 encoded string representing a PNG image.
I've tried the following:
const { Camera } = Plugins;
const image = await Camera.getPhoto({
quality: 90,
allowEditing: true,
resultType: CameraResultType.Base64
});
const rawData = atob(image.base64String);
const blob = new Blob([rawData], { type: 'image/png' });
But the blob ends up not being a valid image.
Any help is appreciated.
Using: @angular/core: 9.1.4, @ionic/angular: 5.1.0, @capacitor/core: 2.1.1
Upvotes: 10
Views: 8957
Reputation: 2231
I use this:
import {decode} from "base64-arraybuffer";
const cameraPhoto = await Camera.getPhoto({
resultType: CameraResultType.Base64,
}
const blob = new Blob([new Uint8Array(decode(cameraPhoto.base64String))], {
type: `image/${cameraPhoto.format}`,
});
and if it needs to be converted to a file:
const file = new File([blob], "Name", {
lastModified: moment().unix(),
type: blob.type,
});
Upvotes: 16
Reputation: 301
You need to take the byte characters provided by atob
and convert it to a byte array, which can then be used to generate a Blob
:
const rawData = atob(image.base64String);
const bytes = new Array(rawData.length);
for (var x = 0; x < rawData.length; x++) {
bytes[x] = rawData.charCodeAt(x);
}
const arr = new Uint8Array(bytes);
const blob = new Blob([arr], {type: 'image/png'});
Upvotes: 10