1.我们在看代码时经常在img或css背景图片中看到:
src=”data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAMAAAAOusbgAAAAeFBMVEUAwAD///+U5ZTc9twOww7G8MYwzDCH4==”src或 url() 中有一大串编码。它把一些 8-bit 数据翻译成标准 ASCII 字符,网上有很多免费的base64 编码和解码的工具, 后面跟的一串代码就相当于链接地址。
2.目前,Data URL scheme 支持的类型:
data:,文本数据data:text/plain,文本数据data:text/html,HTML代码data:text/html;base64,base64编码的HTML代码data:text/css,CSS代码data:text/css;base64,base64编码的CSS代码data:text/JavaScript,Javascript代码data:text/javascript;base64,base64编码的Javascript代码data:image/gif;base64,base64编码的gif图片数据data:image/png;base64,base64编码的png图片数据data:image/jpeg;base64,base64编码的jpeg图片数据data:image/x-icon;base64,base64编码的icon图片数据
3.js将图片转化为pase64
function ImgToBase64(url, callback, outputFormat){ var canvas = document.createElement('CANVAS'), ctx = canvas.getContext('2d'), img = new Image; img.crossOrigin = 'Anonymous'; img.onload = function(){ canvas.height = img.height; canvas.width = img.width; ctx.drawImage(img,0,0); var dataURL = canvas.toDataURL(outputFormat || 'image/png'); callback.call(this, dataURL); canvas = null; }; img.src = url;} convertImgToBase64('http://bit.ly/18g0VNp', function(base64Img){ // Base64DataURL});
.