问题描述
我想通过JavaScript加载本地图像文件并将其转换为Base64。我不想在浏览器中显示图像。
如果您使用过Python,则有一个用于此任务的图像处理库(OpenCV)。我需要执行相同的任务,但是要使用JavaScript。
在这方面,我找到了以下存储库:
https://github.com/renanbastos93/image-to-base64
当我运行以下代码时,它可以正常运行。
const imagetoBase64 = require('image-to-base64');
imagetoBase64("1.jpg") // Path to the image
.then(
(response) => {
console.log(response); // "cGF0aC90by9maWxlLmpwZw=="
}
)
.catch(
(error) => {
console.log(error); // Logs an error if there was one
}
)
但是,我不想在控制台中打印“响应”。我想将“响应”保存到变量中并返回。我尝试了以下代码:
const imagetoBase64 = require('image-to-base64');
imagetoBase64("1.jpg") // Path to the image
.then(
(response) => {
//console.log(response)
var image_base64 = response; // response is Base64
return image_base64
}
)
.catch(
(error) => {
console.log(error); // Logs an error if there was one
}
)
console.log(typeof image_base64)
运行上面的代码时,变量“ image_base64”位于“未定义”中。
我是JavaScript领域的新手,如果您能对此进行指导,我将不胜感激。当我在Python中定义函数时,我将返回任何所需的变量。但是,上述结构完全不同,我不太了解。
解决方法
尝试使用此命令
var image = Filereader()。result.replace(/ ^ data:。+; base64,/,'');
,//对于javascript var x = document.getElementById(“ myImg”);
//对于html
img id =“ myImg” src =“ image_location / imageName.ext”
上面的html代码不是正确的语法,而只是伪代码。 在图像所在的位置创建一个新文件夹。 image_location是该文件夹的名称。您可以使用任何想要的名称。