1.页面上的图片,转换成base64格式,可以通过canvas 的 toDataURL
例子:给定图片的url 将图片转换为base64
var imageSrc = "../images/0.jpg"; // 图片的URL
//@param image:Image 对象,ext:图片的格式(jpg)
function getBase64Image(image,ext){
var canvas = document.createElement("canvas");
canvas.width = image.width;
canvas.height = image.height;
var context = canvas.getContext("2d");
context.drawImage(image,0,0,image.width,image.height);
// 这里是不支持跨域的
var base64 = canvas.toDataURL("image/"+ext);
return base64;
}
var image = new Image();
//image.crossOrigin=""; // 如果图片是跨域的,填上"*"或者"anonymous" 核心是请求头中包含了 Origin: "anonymous"或"*" 字段,响应头中就会附加上 Access-Control-Allow-Origin: * 字段,
image.src = imageSrc;
image.onload = function(){
var ext = imageSrc.substring(imageSrc.lastIndexOf(".")+1);
var base64 = getBase64Image(image,ext);
console.log(base64);
//alert(base64);
}
2.将已经显示在页面上的图片转换为base64
<img src="https://img.alicdn.com/bao/uploaded/TB1qimQIpXXXXXbXFXXSutbFXXX.jpg" alt="" crossorigin="*">
如果是跨域的图片,要加上 crossorigin 属性
setTimeout(function(){
console.log(getBase64Image(document.getElementsByTagName("img")[0],"jpg"));
},3000);
2.文件选择图片时,转换成base64
使用FileReader api readAsDataURL FileReader AIP 地址 https://developer.mozilla.org/en-US/docs/Web/API/FileReader
例子:
<input type="file" value="sdgsdg" id="demo_input" />
window.onload = function(){
var file = document.getElementById("demo_input");
file.onchange = function(){
var file = this.files[0];
alert(file.type);
if(!/image/.test(file.type));
return;
var reader = new FileReader();
reader.readAsDataURL(file)
reader.onload = function(){
alert(this.result);
}
}
}