图片转base64
2018-06-05 本文已影响0人
大大的小小小心愿
一、通过图片路径将图片转base64:canvas中的toDataURL
function getBase64Image(img) {
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var context = cavas.getContext('2d');
context.beginPath();
context.drawImage(img,0,0,img.width,img.height);
var imgType = img.src.substring(img.src,lastIndexOf(".")+1).toLowerCase(); // 图片类型
var imgBase64 = canvas.toDataURL("image/"+imgType);
return imgBase64;
}
var img = "a.jpg";
var image = new Image();
image.src = img;
image.onload = function(){
var base64 = getBase64Image(image);
// console.log(base64);
}
二、只支持file、blob类型:readAsDataURL
var img = document.getElementById('img');
function toBase64() {
var fileReader = new FileReader();
console.log(img.files[0]);
fileReader.readAsDataURL(img.files[0]);
fileReader.onload = function (ev) {
var imgBase64Data = this.result;
document.getElementById('base64String').value = imgBase64Data;
document.getElementById('backImg').setAttribute('src',imgBase64Data); // base64转 img图片
}
}