如何使用 JavaScript 将图像转换为 base64 字符串?
javascriptobject oriented programmingfront end technology更新于 2024/7/23 5:00:17
要使用 JavaScript 将图像转换为 base64 字符串,请使用 FileReader API。您可以尝试运行以下代码来获取图像的 base64string −
示例
<!DOCTYPE html>
<html>
<body>
<script>
function toDataURL(url, callback) {
var httpRequest = new XMLHttpRequest();
httpRequest.onload = function() {
var fileReader = new FileReader();
fileReader.onloadend = function() {
callback(fileReader.result);
}
fileReader.readAsDataURL(httpRequest.response);
};
httpRequest.open('GET', url);
httpRequest.responseType = 'blob';
httpRequest.send();
}
toDataURL('https://www.tutorialspoint.com/videotutorials/images/tutor_connect_home.jpg', function(dataUrl) {
document.write('Result in string:', dataUrl)
})
</script>
</body>
</html>
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/
打印
下一节:如何修复 Internet Explorer 浏览器的 JavaScript 中的 Array indexOf()? ❯❮ 上一节:如何将二进制 NodeJS Buffer 转换为 JavaScript ArrayBuffer?

