首页 > 解决方案 > I am unable to convert an ArrayBuffer stored in DB to an image

问题描述

My app takes a photo which is converted to an ArrayBuffer and stored in DB as such. I want to then retrieve that data and convert it to an image without storing the resulting file.

I have looked RN-Fetch-blob and FileReader but am unclear about a few things.

Here is what I've tried with variable combinations after reading many different posts on the issue:

var arrayBufferView = new Uint8Array(expense.receipt);
const blob = new Blob(expense.receipt,"image/jpeg" ); 
//const blob = new Blob([expense.receipt],"image/jpeg" ); <-error
 //const blob = new Blob(arrayBufferView,"image/jpeg" ); <-error

//console.log (blob);
const fileReaderInstance = new FileReader();
fileReaderInstance.readAsDataURL(blob);  // tried 'readAsBufferArray' but RN complained that that function is not implemented.
fileReaderInstance.onload = () => {
 const base64data = fileReaderInstance.result;                
 console.log(base64data);
};
 var imageBase64 = 'data:'+"image/jpeg"+';base64,'+blob;
 console.log (imageBase64)
});

What am I doing wrong?

Thanks in advance.

标签: javascriptreact-native

解决方案


将图像从Array Buffer转换为:

斑点:

var arrayBufferView = new Uint8Array(expense.receipt);
const blob = new Blob([arrayBufferView], {type:"image/jpeg"} );
const img = createObjectURL(blob); //Remember to revokeObjectURL when done

Base64:

var arrayBufferView = new Uint8Array(expense.receipt);
const charArr = arrayBufferView.reduce((data, byte)=> (data + String.fromCharCode(byte)), ''));
const img = btoa(charArr);

推荐阅读