我想将图像从reactjs转换为base64,以将该图像保存在mongo中,而不将图像上传到服务器,然后如果不直接转换图像,则将其转换
答案 0 :(得分:2)
我分享我的解决方案
const getEmergencyFoundImg = urlImg => {
var img = new Image();
img.src = urlImg;
img.crossOrigin = 'Anonymous';
var canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d');
canvas.height = img.naturalHeight;
canvas.width = img.naturalWidth;
ctx.drawImage(img, 0, 0);
var b64 = canvas.toDataURL('image/png').replace(/^data:image.+;base64,/, '');
return b64;
};
我建议使用async / await调用此函数以构建帖子的对象。
该方法从以下来源提取它: https://base64.guru/developers/javascript/examples/convert-image