function img2Base64(img) { var imgData = getPixels(img).data; var imgWidth = getPixels(img).width; var imgHeight = getPixels(img).height; var bin = ""; for (var i = 0; i < imgData.length; i++) { bin += base.numToString(imgData[i]); } bin = bin + base.stringToBin("$$" + imgWidth + "," + imgHeight + "$$"); return base.binToBase64(bin); }
将图片Base64数据进行解码
解码是编码的逆过程。过程大致为:
将图片的Base64信息进行解码,得到包含图片像素信息和宽高度信息的二进制序列;然后将这个二进制序列解码成字符串,获取高度和宽度信息;去除二进制序列中的高度和宽度信息,得到像素信息;根据像素信息生成像素矩阵;根据像素矩阵、宽度和高度创建图片对象ImageData;利用putImageData将图像绘制出来。
具体的代码实现为:
function paint(imgData) { var canvas = document.getElementById("myCanvas"); var ctx = canvas.getContext("2d"); ctx.fillRect(0, 0, imgData.width, imgData.height); ctx.putImageData(imgData, 0, 0); } function base642img(data) { var str = base.BinToStr(base.base64ToBin(data)); var imgWidth = str.match(/\$\$(\d+),(\d+)\$\$$/, "")[1]; var imgHeight = str.match(/\$\$(\d+),(\d+)\$\$$/, "")[2] var imgData = base.base64ToBin(data).replace(base.stringToBin("$$" + imgWidth + "," + imgHeight + "$$"), ""); var ImageDataArray = new Uint8ClampedArray(imgWidth * imgHeight * 4); for (var i = 0; i < ImageDataArray.length; i++) { ImageDataArray[i] = parseInt(imgData.substr(i * 8, 8), 2); } return new ImageData(ImageDataArray, imgWidth, imgHeight); }
您可能感兴趣的文章: