js对明文和图片进行base64编码加密

base64编码和解码

const rich = btoa("I have money, a lot, fully 10 yuan.") // 编码
console.log(rich) // SSBoYXZlIG1vbmV5LCBhIGxvdCwgZnVsbHkgMTAgeXVhbi4=


const HowMuchMoneyIHave = atob(rich) // 解码
console.log(HowMuchMoneyIHave.split(',')[2]) //  fully 10 yuan.

以上是对ASCII代码进行加密,下面对非ASCII代码加密

function b64Encode(str) {
     
	return btoa(encodeURIComponent(str)); // 先转码再编码
}
function b64Decode(str) {
     
	return decodeURIComponent(atob(str)); // 先解码再转码
}
let IHaveMoney = b64Encode('我有钱'); 
console.log(IHaveMoney); // JUU2JTg4JTkxJUU2JTlDJTg5JUU5JTkyJUIx
console.log(b64Decode(IHaveMoney)); // 我有钱

base64对图片编码

<body>
	<img src="" class="img" />
	<script>
		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("images/" + ext);
			return dataUrl;
		};
		var img = "./img/b5.jpg";  // 图片路径
		var image = new Image();
		image.src = img;
		image.onload = function() {
     
			var base64 = getBase64Image(image);
			document.getElementsByClassName("img")[0].setAttribute("src", base64)
		}
	</script>
</body>

你可能感兴趣的:(js,base64加密文字和图片,js,base64)