From: https://bytenota.com/javascript-convert-image-to-base64-string/
his post shows you two approaches how to convert an image to a Base64 string using JavaScript: HTML5 Canvas
and FileReader
.
1. Approach 1: HTML5 Canvas
example.js
function toDataURL(src, callback) {
var image = new Image();
image.crossOrigin = 'Anonymous';
image.onload = function() {
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
canvas.height = this.naturalHeight;
canvas.width = this.naturalWidth;
context.drawImage(this, 0, 0);
var dataURL = canvas.toDataURL('image/jpeg');
callback(dataURL);
};
image.src = src;
}
The above code we load the image into Image
object, draw it to the canvas and then convert it to Base64 image data URL.
2. Approach 2: FileReader
example.js
function toDataURL(src, callback) {
var xhttp = new XMLHttpRequest();
xhttp.onload = function() {
var fileReader = new FileReader();
fileReader.onloadend = function() {
callback(fileReader.result);
}
fileReader.readAsDataURL(xhttp.response);
};
xhttp.responseType = 'blob';
xhttp.open('GET', src, true);
xhttp.send();
}
The above code we load the image as Blob via XMLHttpRequest
, then use FileReader
to convert the image to Base64 image data URL.
Use the function:
toDataURL('https://www.gravatar.com/avatar', function(dataURL) {
// do something with dataURL
console.log(dataURL);
});
但是这两种都是需要图片服务器允许跨域资源访问才可以,对于第二种方法,如果图片服务器不允许跨域资源访问, XMLHttpRequest的onload事件就不会执行.
注: 在实际的应用中,发现Canvas转换gif动图的时候只能取到第一帧,结果动图变成了静图,而FileReader方法则可以成功转换动图.下面两段代码分别用来出来本地文件和网络文件:
本地文件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | <! DOCTYPE html> < html > < head > < title >Blob To Base64</ title > < meta http-equiv="Content-type" content="text/html; charset=utf-8"> </ head > < body > < img id="showImg" /> < input type="file" onchange="changeFile(event);" /> </ body > </ html > < script type="text/javascript"> function changeFile(event) { file = event.target.files[0]; var a = new FileReader(); a.onload = function (e) { var base64Str = e.target.result;//获取base64 //下面是测试得到的base64串能否正常使用: document.getElementById('showImg').src = base64Str; } a.readAsDataURL(file); } </ script > |
网络文件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | <! DOCTYPE html> < html > < head > < title >Blob To Base64</ title > < meta http-equiv="Content-type" content="text/html; charset=utf-8"> </ head > < body > < img id="showImg" /> < input type="button" value="Test" onclick="TestBase64();" /> </ body > </ html > < script type="text/javascript"> function TestBase64() { var fileUrl = "http://29e5534ea20a8.cdn.sohucs.com/c_zoom,h_86/c_cut,x_8,y_0,w_225,h_150/os/news/e4337401e7ebeac6f7cdb52fac9807e5.gif" toDataURL(fileUrl, function(base64) { document.getElementById('showImg').src = base64; }); } function toDataURL(src, callback) { var xhttp = new XMLHttpRequest(); xhttp.onload = function() { var fileReader = new FileReader(); fileReader.onloadend = function() { callback(fileReader.result); } fileReader.readAsDataURL(xhttp.response); }; xhttp.responseType = 'blob'; xhttp.open('GET', src, true); xhttp.send(); } </ script > |
另外找动图可以到这里面来找: https://tieba.baidu.com/p/4674320064
分类:
JavaScript
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架