js 将图片转换为base64编码

admin0条评论 35 次浏览

/**
* 将图片转换为Base64
*/
function image2Base64(img) {
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/png”);
return dataURL;
}

/**
* 获取图片Base64编码
*/
function getImgBase64(url){
var base64=””;
var img = new Image();
img.src=url;
img.onload=function(){
base64 = image2Base64(img);
alert(base64);
}
}

getImgBase64(“./image/1.jpg”);


发表评论

? razz sad evil ! smile oops grin eek shock ??? cool lol mad twisted roll wink idea arrow neutral cry mrgreen