javascript - 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.
解决方案
将图像从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);
推荐阅读
- javascript - Gulp [4.0.2] 在异步函数完成时挂起,即使回调已完成
- javascript - 如何从 webpack 配置文件的 src 目录中排除 js 文件?
- ansible - Ansible 的 `become: yes` 有替代方案吗?
- c# - Automapper ValueTransformers from dynamic to a class
- sql - SQL query to get following result
- r - 如何从使用 ggplot() 制作的 QQ 图中删除异常值?
- swift - SwiftUI TextField 中的货币输入
- php - 使用 fread() 在 PHP 中读取 DBF 文件的奇怪行为
- swift - 使用 'case' 模式匹配直接返回结果
- python - Mystic - 如何正确停止优化