Converting base64 bit to a file. Used for images
add this function to tour ts file immediatly after imports
function base64toBlob(base64Data, contentType) {
contentType = contentType || '';const sliceSize = 1024;
const byteCharacters = atob(base64Data);
const bytesLength = byteCharacters.length;
const slicesCount = Math.ceil(bytesLength / sliceSize);
const byteArrays = new Array(slicesCount);
for (var sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {
const begin = sliceIndex * sliceSize;
const end = Math.min(begin + sliceSize, bytesLength);
const bytes = new Array(end - begin);
for (let offset = begin, i = 0; offset < end; ++i, ++offset) {
bytes[i] = byteCharacters[offset].charCodeAt(0);
}
byteArrays[sliceIndex] = new Uint8Array(bytes);
}
return new Blob(byteArrays, { type: contentType });
}
example:
onImagePicked(imageData: string | File){
let imageFile;
if ( typeof imageData === 'string'){
try{
imageFile = base64toBlob(imageData.replace('data:image/png;base64,', ''), 'image/jpeg');
}catch(error){
console.log(error);
return;
}
}else{
imageFile = imageData;
}
this.form.patchValue({image: imageFile});
}
Comments