I tried to convert a JPEG's base64 string to a blob on a Cordova/hybrid app running on iOS 8 using the following function b64toBlob
.
b64toBlob = function(b64, onsuccess, onerror) {
var img = new Image();
img.onerror = onerror;
img.onload = function onload() {
var canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
canvas.toBlob(onsuccess);
};
img.src = b64;
}
However it's giving an error
Uncaught Error: TypeError: undefined is not a function (evaluating 'canvas.toBlob(onsuccess)')
when we do
var imageData = "data:image/jpeg;base64," + imageData
b64toBlob(imageData,
function(imageBlob) {
uploadBlob(imageBlob)
}, function(error) {
console.log(error)
});
How can be work around this error?
Try this out. Please note that dataURI
is assumed to include base64 prefix. (e.g. "data:image/jpeg;base64,"
)
function b64toBlob(dataURI) {
var byteString = atob(dataURI.split(',')[1]);
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
return new Blob([ab], { type: 'image/jpeg' });
}
Usage:
...
var blob = b64toBlob(imageData);
var formData = new FormData();
formData.append("source", blob);
...
fetch("data:image/jpeg;base64," + base64Data)
.then(res => res.blob())
.then(blob => {
console.log(blob);
var url = window.URL.createObjectURL(blob);
});
Please try this simple way
fetch(base64).then(res => return res.blob()).then(blob => console.log(blob));
In short, you can use the following function but if you want more details about this, you can read this post Create a blob from base64 data
const b64toBlob = (b64Data, contentType='', sliceSize=512) => {
const byteCharacters = atob(b64Data);
const byteArrays = [];
for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
const slice = byteCharacters.slice(offset, offset + sliceSize);
const byteNumbers = new Array(slice.length);
for (let i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
const blob = new Blob(byteArrays, {type: contentType});
return blob;
}
I have the same problem. The reason for me is that there is space in the base64 string.base64Str = base64Str.replace(/\s/g, '')
This solved my problem
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With