图片Image转换为base64编码的方法

1、FileReader

通过XMLHttpRequest请求图片Blob数据格式,然后利用FileReader转换为dataURL

function toDataURL(url, callback) {
var xhr = new XMLHttpRequest();
xhr.onload = function() {
var reader = new FileReader();
reader.onloadend = function() {
callback(reader.result);
}
reader.readAsDataURL(xhr.response);
};
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.send();
} toDataURL('https://www.gravatar.com/avatar/d50c83cc0c6523b4d3f6085295c953e0', function(dataUrl) {
console.log('RESULT:', dataUrl)
})

请求可以利用 WHATWG fetchJs来实现

const toDataURL = url => fetch(url)
.then(response => response.blob())
.then(blob => new Promise((resolve, reject) => {
const reader = new FileReader()
reader.onloadend = () => resolve(reader.result)
reader.onerror = reject
reader.readAsDataURL(blob)
})) toDataURL('https://www.gravatar.com/avatar/d50c83cc0c6523b4d3f6085295c953e0').then(dataUrl => {
console.log('RESULT:', dataUrl)
})

优缺点:

  • 某些浏览器缺乏支持
  • 更好的文件压缩
  • 适用其他文件类型

查看支持:

2、Canvas

新建图片,在画布上实现,然后将canvas对象转变为一个dataURL

function toDataURL(src, callback, outputFormat) {
var img = new Image();
img.crossOrigin = 'Anonymous'; // 允许image请求的图片应用到canvas,就像他们在同一个域
img.onload = function() {
var canvas = document.createElement('CANVAS');
var ctx = canvas.getContext('2d');
var dataURL;
canvas.height = this.naturalHeight;
canvas.width = this.naturalWidth;
ctx.drawImage(this, 0, 0);
dataURL = canvas.toDataURL(outputFormat);
callback(dataURL);
};
img.src = src;
if (img.complete || img.complete === undefined) { // 确保对缓存的图片也触发img.onload事件
img.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
img.src = src;
}
} toDataURL(
'https://www.gravatar.com/avatar/d50c83cc0c6523b4d3f6085295c953e0',
function(dataUrl) {
console.log('RESULT:', dataUrl)
}
)

支持的inputFormat:

  • image/pngimage/jpegimage/jpgimage/gifimage/bmpimage/tiffimage/x-iconimage/svg+xmlimage/webpimage/xxx

支持的outputFormat:

  • image/pngimage/jpegimage/webp(chrome)

查看支持:

3、从当前文件系统读取,input读取文件后,利用FileReader进行转换

function encodeImageFileAsURL(element) {
var file = element.files[0];
var reader = new FileReader();
reader.onloadend = function() {
console.log('RESULT', reader.result)
}
reader.readAsDataURL(file);
}
<input type="file" onchange="encodeImageFileAsURL(this)" />
上一篇:爱上MVC3~为下拉列表框添加一个自定义验证规则


下一篇:Android onTouchEvent, onClick及onLongClick的调用机制