1.根据img标签获取base64编码
function getImageBase64(img, ext) {
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, img.width, img.height);
var dataURL = canvas.toDataURL("image/" + ext);
canvas = null;
return dataURL;
}
使用
var user_icon = document.getElementById('icon');
user_icon.src = img_path;
user_icon.onload = function () {
base64 = getImageBase64(user_icon, fileExt);
}
2.根据图片路径获取base64编码
function getUrlBase64(url, ext, callback) {
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
var img = new Image;
img.crossOrigin = 'Anonymous';
img.src = url;
img.onload = function () {
canvas.height = 60;
canvas.width = 85;
ctx.drawImage(img, 0, 0, 60, 85);
var dataURL = canvas.toDataURL("image/" + ext);
callback.call(this, dataURL);
canvas = null;
};
}
使用
getUrlBase64(path, ext, function (base64) {
console.log(base64);
});