js 图片与base64互相转换

js将图片转化为base64

参考地址:http://www.cnblogs.com/mr-wuxiansheng/p/6931077.html

var img = "imgurl";//imgurl 就是你的图片路径  

function getBase64Image(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 ext = img.src.substring(img.src.lastIndexOf(".")+1).toLowerCase();
var dataURL = canvas.toDataURL("image/"+ext);
return dataURL;
} var image = new Image();
image.src = img;
image.onload = function(){
var base64 = getBase64Image(image);
console.log(base64);
}

js将base64转化为图片格式

参考地址:https://segmentfault.com/q/1010000010236626

js直接设置img的src属性为 图片的base64数据即可

document.getElementById('img').setAttribute( 'src', 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0 DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==' );

上一篇:Linux 于 shell 变数 $#,$@,$0,$1,$2 含义解释:


下一篇:20155326《网路对抗》Exp8 WEB基础实践