来自 公司简介 2019-12-07 06:44 的文章
当前位置: 澳门太阳娱乐手机登录 > 公司简介 > 正文

得以落成及利用

Base64 的原理、实现及应用

2016/04/06 · 基础技术 · 1 评论 · Base64

本文作者: 伯乐在线 - Natumsol 。未经作者许可,禁止转载!
欢迎加入伯乐在线 专栏作者。

简介

Base64是一种基于64个可打印字符来表示二进制数据的表示方法。由于2的6次方等于64,所以每6个比特为一个单元,对应某个可打印字符。三个字节有24个比特,对应于4个Base64单元,即3个字节需要用4个可打印字符来表示。它可用来作为电子邮件的传输编码。在Base64中的可打印字符包括字母A-Za-z、数字0-9,这样共有62个字符,此外的两个可打印符号在不同的系统中而不同,一般为+/

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script>
(function(w){

转换原理

Base64的直接数据源是二进制序列(Binary Sequence)。当然,你也可以将图片、文本和音视频转换成二进制序列,再然后转换为Base64编码。我们这里讨论的是如何将二进制转换为Base64编码,对于如何将图片,文本和音视频转换为二进制序列敬请期待。

在转换前,先定义一张索引表,这张表规定了如何转换。
图片 1
转换的时候我们先将二进制序列分组,每6个比特为一组。但是如果编码的字节数不能被3整除,那么最后就会多出1个或两个字节,可以使用下面的方法进行处理:先使用0字节值在末尾补足,使其能够被3整除,然后再进行base64的编码。在编码后的base64文本后加上一个或两个’=’号,代表补足的字节数。也就是说,当最后剩余一个八位字节(一个byte)时,最后一个6位的base64字节块有四位是0值,最后附加上两个等号;如果最后剩余两个八位字节(2个byte)时,最后一个6位的base字节块有两位是0值,最后附加一个等号。 参考下表:
图片 2

var quse = {
colors : [],
getUrl : function(obj){

用JavaScript实现Base64

原理明白了以后,实现起来就很容易了。

JavaScript

define(function(require, exports, module) { var code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""); //索引表 /** * @author natumsol@gmail.com * @description 将二进制序列转换为Base64编码 * @param {String} * @return {String} */ function binToBase64(bitString) { var result = ""; var tail = bitString.length % 6; var bitStringTemp1 = bitString.substr(0, bitString.length - tail); var bitStringTemp2 = bitString.substr(bitString.length - tail, tail); for (var i = 0; i < bitStringTemp1.length; i += 6) { var index = parseInt(bitStringTemp1.substr(i, 6), 2); result += code[index]; } bitStringTemp2 += new Array(7 - tail).join("0"); if (tail) { result += code[parseInt(bitStringTemp2, 2)]; result += new Array((6 - tail) / 2

  • 1).join("="); } return result; } /** * @author natumsol@gmail.com * @description 将base64编码转换为二进制序列 * @param {String} * @return {String} */ function base64ToBin(str) { var bitString = ""; var tail = 0; for (var i = 0; i < str.length; i++) { if (str[i] != "=") { var decode = code.indexOf(str[i]).toString(2); bitString += (new Array(7 - decode.length)).join("0") + decode; } else { tail++; } } return bitString.substr(0, bitString.length - tail * 2); } /** * @description 将字符转换为二进制序列 * @param {String} str * @return {String} */ function stringToBin(str) { var result = ""; for (var i = 0; i < str.length; i++) { var charCode = str.charCodeAt(i).toString(2); result += (new Array(9 - charCode.length).join("0") + charCode); } return result; } /** * @description 将二进制序列转换为字符串 * @param {String} Bin */ function BinToStr(Bin) { var result = ""; for (var i = 0; i < Bin.length; i += 8) { result += String.fromCharCode(parseInt(Bin.substr(i, 8), 2)); } return result; } exports.base64 = function(str) { return binToBase64(stringToBin(str)); } exports.decodeBase64 = function(str) { return BinToStr(base64ToBin(str)); } })
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
define(function(require, exports, module) {
 
    var code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""); //索引表
 
    /**
     * @author natumsol@gmail.com
     * @description 将二进制序列转换为Base64编码
     * @param  {String}
     * @return {String}
     */
    function binToBase64(bitString) {
        var result = "";
        var tail = bitString.length % 6;
        var bitStringTemp1 = bitString.substr(0, bitString.length - tail);
        var bitStringTemp2 = bitString.substr(bitString.length - tail, tail);
        for (var i = 0; i &lt; bitStringTemp1.length; i += 6) {
            var index = parseInt(bitStringTemp1.substr(i, 6), 2);
            result += code[index];
        }
        bitStringTemp2 += new Array(7 - tail).join("0");
        if (tail) {
            result += code[parseInt(bitStringTemp2, 2)];
            result += new Array((6 - tail) / 2 + 1).join("=");
        }
        return result;
    }
 
    /**
     * @author natumsol@gmail.com
     * @description 将base64编码转换为二进制序列
     * @param  {String}
     * @return {String}
     */
    function base64ToBin(str) {
        var bitString = "";
        var tail = 0;
        for (var i = 0; i &lt; str.length; i++) {
            if (str[i] != "=") {
                var decode = code.indexOf(str[i]).toString(2);
                bitString += (new Array(7 - decode.length)).join("0") + decode;
            } else {
                tail++;
            }
        }
        return bitString.substr(0, bitString.length - tail * 2);
    }
 
    /**
     * @description 将字符转换为二进制序列
     * @param  {String} str
     * @return {String}    
     */
    function stringToBin(str) {
        var result = "";
        for (var i = 0; i &lt; str.length; i++) {
            var charCode = str.charCodeAt(i).toString(2);
            result += (new Array(9 - charCode.length).join("0") + charCode);
        }
        return result;
    }
    /**
     * @description 将二进制序列转换为字符串
     * @param {String} Bin
     */
    function BinToStr(Bin) {
        var result = "";
        for (var i = 0; i &lt; Bin.length; i += 8) {
            result += String.fromCharCode(parseInt(Bin.substr(i, 8), 2));
        }
        return result;
    }
    exports.base64 = function(str) {
        return binToBase64(stringToBin(str));
    }
    exports.decodeBase64 = function(str) {
        return BinToStr(base64ToBin(str));
    }
})

var url;

将图片数据进行Base64编码

将图片数据转换为Base64,首先要获取到图片的二进制数据。图片的二进制数据可以通过canvas接口得到。具体实现为:

JavaScript

function getCanvas(w, h) { var c = document.createElement('canvas'); c.width = w; c.height = h; return c; } function getPixels(img) { var c = getCanvas(img.width, img.height); var ctx = c.getContext('2d'); ctx.drawImage(img, 0, 0); return ctx.getImageData(0, 0, c.width, c.height); }

1
2
3
4
5
6
7
8
9
10
11
12
13
function getCanvas(w, h) {
var c = document.createElement('canvas');
c.width = w;
c.height = h;
return c;
}
 
function getPixels(img) {
var c = getCanvas(img.width, img.height);
var ctx = c.getContext('2d');
ctx.drawImage(img, 0, 0);
return ctx.getImageData(0, 0, c.width, c.height);
}

取到图片的二进制数据后,接下来就要进行编码了。因为图片不仅包含像素信息,还包含长度,宽度信息。所以在编码像素信息的同时也应将宽度和高度信息按某一约定进行编码,我是这样处理的:

  1. 将图片的像素数值数据转换为二进制序列;
  2. 将宽度和高度信息组合成字符串$$width,height$$,转换为二进制序列;
  3. 将图片像素信息的二进制序列和图片宽高度的二进制序列组合起来,然后再进行Base64的编码

具体实现为:

JavaScript

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); }

1
2
3
4
5
6
7
8
9
10
11
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 &lt; imgData.length; i++) {
bin += base.numToString(imgData[i]);
}
bin = bin + base.stringToBin("$$" + imgWidth + "," + imgHeight + "$$");
return base.binToBase64(bin);
}

url = window.webkitURL.createObjectURL(obj.files.item(0));

将图片Base64数据进行解码

解码是编码的逆过程。过程大致为:

  1. 将图片的Base64信息进行解码,得到包含图片像素信息和宽高度信息的二进制序列;
  2. 然后将这个二进制序列解码成字符串,获取高度和宽度信息;
  3. 去除二进制序列中的高度和宽度信息,得到像素信息;
  4. 根据像素信息生成像素矩阵;
  5. 根据像素矩阵、宽度和高度创建图片对象ImageData
  6. 利用putImageData将图像绘制出来。

具体的代码实现为:

JavaScript

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); }

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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 &lt; ImageDataArray.length; i++) {
ImageDataArray[i] = parseInt(imgData.substr(i * 8, 8), 2);
}
return new ImageData(ImageDataArray, imgWidth, imgHeight);
 
}

return url;

DEMO演示

在线演示: DEMO 
源码请移步 Github 
图片 3 

打赏支持我写出更多好文章,谢谢!

打赏作者

},
bing : function(obj){

打赏支持我写出更多好文章,谢谢!

任选一种支付方式

图片 4 图片 5

2 赞 3 收藏 1 评论

var self = this;

关于作者:Natumsol

图片 6

阿里巴巴 前端工程师 个人主页 · 我的文章 · 5 ·    

图片 7

obj.onchange = function(){

var img = self.createImage(self.getUrl(this));

}

},
createImage : function(url){

var img = new Image;
img.src = url;

var self = this;

img.onload = function(){
self.putImage(img);
}

},
putImage : function(img){

var canvas = document.getElementById("canvas");

var ctx = canvas.getContext("2d");

var imgWidth = canvas.width = img.width;

var imgHeight = canvas.height = img.height;

canvas.style.marginLeft = -imgWidth/2+"px";

ctx.drawImage(img , 0,0,imgWidth,imgHeight,0,0,imgWidth,imgHeight);

this.bindCanvas(canvas);

},
start : function(id){
var fileInput = document.getElementById("fileInput");
this.bing(fileInput);
},
bindCanvas : function(canvas){

var self = this;

canvas.onmousedown = function(e){

this.down = true;

this.style.cursor = "crosshair";

if( this.down ){
var x = e.pageX , y = e.pageY;

var left = x - this.offsetLeft , top = y - this.offsetTop;

self.getColor(this , {x : left , y : top});

}

}

canvas.onmousemove = function(e){

if( this.down ){
var x = e.pageX , y = e.pageY;

var left = x - this.offsetLeft , top = y - this.offsetTop;

self.getColor(this , {x : left , y : top});

}

}

canvas.onmouseup = function(){
this.down = false;
this.style.cursor = "default"
}

},
getColor : function(canvas , obj){

var ctx = canvas.getContext("2d");

var imgData = ctx.getImageData(obj.x , obj.y , 1 , 1);

var self = this;

var r = imgData.data[0] , g = imgData.data[1] , b = imgData.data[2];

var span = document.getElementById("mianban").getElementsByTagName("span")[0];
var i = document.getElementById("mianban").getElementsByTagName("i")[0];
var btn = document.getElementById("mianban").getElementsByTagName("button")[0];

span.innerHTML = "颜色 : " + this.RGB(r,g,b);

i.style.background = this.RGB(r,g,b);

this.colors = [r,g,b];

if(!btn.jianting){

btn.jianting = true;

btn.onclick = function(){

if(confirm("是否需要模糊匹配?")){

self.quse(canvas, ctx ,true)

}else{

self.quse(canvas, ctx ,false)

}

}

}

},
quse : function(canvas , ctx , o){

var data = ctx.getImageData(0,0,canvas.width,canvas.height);

var r = this.colors[0] , g = this.colors[1] , b = this.colors[2];

for(var i = 0 ; i < data.data.length; i+=4){

var newdata = data.data;

var r1 = newdata[i+0] , g1 = newdata[i+1] , b1 = newdata[i+2];

if(o){

var r3 = (r - r1) / 256 , g3 = (g - g1) / 256 , b3 = (b - b1) / 256;

var bai = (1 - Math.sqrt(r3 * r3 + g3 * g3 + b3 * b3)) * 100;

if(bai > 90){

data.data[i+3] = 0;

}

}else{

if(r1 == r && g1 == g && b1 == b){

data.data[i+3] = 0;
}

}

}

ctx.clearRect(0,0,canvas.width,canvas.height);

ctx.putImageData(data,0,0);

},
RGB : function(r,g,b){

var str = "#" + r.toString(16) + "" + g.toString(16) + "" + b.toString(16);

return str;

}

}

w.quse = quse;

})(window);

</script>
<style type="text/css">
html{
background: #f0f0f0;
}
*{
margin: 0;
padding: 0;
}
canvas{
background: transparent;
position: absolute;
left: 50%;
top: 120px;
}
#fileInput{
opacity: 0;
height: 40px;
width: 120px;
}
button{
background: deepskyblue;
color: #fff;
width: 120px;
height: 40px;
border: 0;
border-radius: 4px;
outline: none;
}
.wrap{
padding-top: 50px;
position: absolute;
width: 300px;
left: 50%;
margin-left: -150px;
}
.wrap div{
position: absolute;
right: 0;
top: 45px;
width: 120px;
}
.wrap div button{
position: absolute;
top: 0;
z-index: -1;
}

#mianban{
background: rgba(255,255,255,.8);
width: 160px;
padding: 10px 20px;
position: absolute;
right: 0;
height: 330px;
top: 50%;
margin-top: -175px;
color: #333;
border-radius: 4px 0 0 4px;
border: 1px solid #CCCCCC;
}

#mianban p:first-child{
margin-top: 30px;
}
#mianban p i{
display: inline-block;
width: 20px;
height: 20px;
border: 1px solid #00BFFF;
border-radius: 2px;
position: relative;
left: 10px;
top: 4px;
background: rgb(230,230,230);
}
#mianban button{
display: block;
position: static;
margin: 0 auto;
margin-top: 30px;
}
</style>
</head>
<body>

<div class="wrap">
<h1>去色系统</h1>
<div>
<input type="file" id = "fileInput"/>
<button>打开图片</button>
</div>
</div>

<div id="mianban">

<p><span>颜色</span><i></i></p>
<button>去色</button>
</div>

<canvas id = "canvas"></canvas>

<script>

quse.start("fileInput");

</script>

</body>
</html>

本文由澳门太阳娱乐手机登录发布于公司简介,转载请注明出处:得以落成及利用

关键词: