澳门新萄京官方网站-www.8455.com-澳门新萄京赌场网址

js对图片base64编码字符串进行解码并输出图像示例

2019-06-16 作者:澳门新萄京赌场网址   |   浏览(54)

Base64 的法则、完毕及利用

2016/04/06 · 基本功工夫 · 1 评论 · Base64

正文笔者: 伯乐在线 - Natumsol 。未经笔者许可,禁止转发!
招待到场伯乐在线 专辑作者。

简介

Base64是一种基于69个可打字与印刷字符来表示二进制数据的表示方法。由于2的6次方等于64,所以每6个比特为三个单元,对应有些可打印字符。多少个字节有二十三个比特,对应于4个Base64单元,即3个字节供给用4个可打字与印刷字符来表示。它可用来作为电子邮件的传输编码。在Base64中的可打字与印刷字符包罗字母A-Za-z、数字0-9,那样共有61个字符,其它的多少个可打印符号在不相同的系统中而不一样,一般为 /

复制代码 代码如下:

在重重时候,大家直接在url中传递汉语参数时,读到的华语都是乱码,那么大家相应怎么将那么些参数转变呢?

<!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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ";
<html xmlns=";
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<style>
body{padding-left:75px;background-color:beige}
</style>
<script>
///////////////////////////
//base64编码的GIF图像解码
//By Mozart0
//2005/10/29
////////////////////

下边大家来介绍一下办法
1、大家新建叁个 UrlEncode.js 然后将上边包车型大巴代码拷贝进去

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

/*
* base64编码
*/
var base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 /";
var base64DecodeChars = new Array(
  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63,
  52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1,
  -1, 0, 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, -1, -1, -1, -1, -1,
  -1, 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, -1, -1, -1, -1, -1);
function base64encode(str) {
  var out, i, len;
  var c1, c2, c3;
  len = str.length;
  i = 0;
  out = "";
  while(i < len) {
c1 = str.charCodeAt(i ) & 0xff;
if(i == len)
{
out = base64EncodeChars.charAt(c1 >> 2);
   out = base64EncodeChars.charAt((c1 & 0x3) << 4);
   out = "==";
   break;
}
c2 = str.charCodeAt(i );
if(i == len)
{
   out = base64EncodeChars.charAt(c1 >> 2);
   out = base64EncodeChars.charAt(((c1 & 0x3)<< 4) | ((c2 & 0xF0) >> 4));
   out = base64EncodeChars.charAt((c2 & 0xF) << 2);
   out = "=";
   break;
}
c3 = str.charCodeAt(i );
out = base64EncodeChars.charAt(c1 >> 2);
out = base64EncodeChars.charAt(((c1 & 0x3)<< 4) | ((c2 & 0xF0) >> 4));
out = base64EncodeChars.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >>6));
out = base64EncodeChars.charAt(c3 & 0x3F);
  }
  return out;
}
function base64decode(str) {
  var c1, c2, c3, c4;
  var i, len, out;
  len = str.length;
  i = 0;
  out = "";
  while(i < len) {
/* c1 */
do {
   c1 = base64DecodeChars[str.charCodeAt(i ) & 0xff];
} while(i < len && c1 == -1);
if(c1 == -1)
   break;
/* c2 */
do {
   c2 = base64DecodeChars[str.charCodeAt(i ) & 0xff];
} while(i < len && c2 == -1);
if(c2 == -1)
   break;
out = String.fromCharCode((c1 << 2) | ((c2 & 0x30) >> 4));
/* c3 */
do {
   c3 = str.charCodeAt(i ) & 0xff;
   if(c3 == 61)
  return out;
   c3 = base64DecodeChars[c3];
} while(i < len && c3 == -1);
if(c3 == -1)
   break;
out = String.fromCharCode(((c2 & 0XF) << 4) | ((c3 & 0x3C) >> 2));
/* c4 */
do {
   c4 = str.charCodeAt(i ) & 0xff;
   if(c4 == 61)
  return out;
   c4 = base64DecodeChars[c4];
} while(i < len && c4 == -1);
if(c4 == -1)
   break;
out = String.fromCharCode(((c3 & 0x03) << 6) | c4);
   }
  return out;
}
function utf16to8(str) {
  var out, i, len, c;
  out = "";
  len = str.length;
  for(i = 0; i < len; i ) {
c = str.charCodeAt(i);
if ((c >= 0x0001) && (c <= 0x007F)) {
   out = str.charAt(i);
} else if (c > 0x07FF) {
   out = String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
   out = String.fromCharCode(0x80 | ((c >> 6) & 0x3F));
   out = String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
} else {
   out = String.fromCharCode(0xC0 | ((c >> 6) & 0x1F));
   out = String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
}
  }
  return out;
}
function utf8to16(str) {
  var out, i, len, c;
  var char2, char3;
  out = "";
  len = str.length;
  i = 0;
  while(i < len) {
c = str.charCodeAt(i );
switch(c >> 4)
{
  case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7:
   // 0xxxxxxx
   out = str.charAt(i-1);
   break;
  case 12: case 13:
   // 110x xxxx  10xx xxxx
   char2 = str.charCodeAt(i );
   out = String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));
   break;
  case 14:
   // 1110 xxxx 10xx xxxx 10xx xxxx
   char2 = str.charCodeAt(i );
   char3 = str.charCodeAt(i );
   out = String.fromCharCode(((c & 0x0F) << 12) |
    ((char2 & 0x3F) << 6) |
    ((char3 & 0x3F) << 0));
   break;
}
}
  return out;
}
/*
* base64编码 End
*/
var m = 'hello';
m = base64encode(m);

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

//建立GIF类的目的
//类GIF在此函数内部定义
//str64:gif文件的Base64编码字符串
//成功重回成立的GIF对象
//退步重临null
function getGif(str64){
var bytes=decodeBase64(str64);
if(!bytes){
alert("错误:无效的Base64编码");
return null;
}
var gif=new GIF();
for(var i=0;i<6;i )
gif.version =String.fromCharCode(bytes[i]);
if(gif.version.slice(0,3)!="GIF"){
alert("错误:非Gif图像格式");
return null;
}
gif.width=bytes[i]|(bytes[i 1]<<8);
gif.height=bytes[i 2]|(bytes[i 3]<<8);
var f=bytes[i 4];
gif.colorResolution=(f>>4&0x7) 1;
gif.sorted=(f&0x8)?true:false;
gif.backgroundIndex=bytes[i 5];
gif.pixelAspectRadio=bytes[i 6];
if(f&0x80){
gif.globalPalette=[];
i =getPalette(i 7,bytes,gif.globalPalette,2<<(f&0x7));
}
i =7;
for(var j=i;j<bytes.length;j )
if(bytes[j]==0x21&&bytes[j 1]==0xf9)
break;
if(j==bytes.length){
for(;i<bytes.length;i )
if(bytes[i]==0x2c)
break;
if(i==bytes.length){
alert("错误:找不到图像数据");
return null;
}
var f=new GIF_Frame();
if(!getSingleFrame(i,f))
return null;
else
gif.frames.push(f);
}
else{
i=j;
do{
var f=new GIF_Frame();
var t=getSingleFrame(i,f);
if(!t)
return null;
gif.frames.push(f);
for(i =t;i<bytes.length;i )
if(bytes[i]==0x21&&bytes[i 1]==0xf9)
break;
}
while(i<bytes.length);
}
return gif;

复制代码 代码如下:

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

//内部进程,生成色表
function getPalette(pos,s,d,len){
len*=3;
for(var i=pos;i<pos len;i =3)
d.push('#' (s[i]<=0xf?"0":"") s[i].toString(16)
(s[i 1]<=0xf?"0":"") s[i 1].toString(16)
(s[i 2]<=0xf?"0":"") s[i 2].toString(16));
return len;
}

//JS版的Server.UrlEncode编码函数
String.prototype.UrlEncodeGB2312 = function () {
var str = this;
str = str.replace(/./g, function (sHex) {
window.EnCodeStr = "";
window.sHex = sHex;
window.execScript('window.EnCodeStr=Hex(Asc(window.sHex))', "vbscript");
return window.EnCodeStr.replace(/../g, "%{blogcontent}amp;");
});
return str;
}
String.prototype.UrlEncode = function () {
var s = escape(this);
var sa = s.split("%");
var retV = "", retE = "";
if (sa[0] != "") {
retV = sa[0];
}
for (var i = 1; i < sa.length; i ) {
if (sa[i].substring(0, 1) == "u") {
retV = Hex2Utf8(Str2Hex(sa[i].substring(1, 5)));
if (sa[i].length > 4)
retV = sa[i].substring(5);
}
else retV = "%" sa[i];
}
return retV;
}
function Str2Hex(s) {
var c = "";
var n;
var ss = "0123456789ABCDEF";
var digS = "";
for (var i = 0; i < s.length; i ) {
c = s.charAt(i);
n = ss.indexOf(c);
digS = Dec2Dig(eval(n));
}
return digS;
}
function Dec2Dig(n1) {
var s = "";
var n2 = 0;
for (var i = 0; i < 4; i ) {
n2 = Math.pow(2, 3 – i);
if (n1 >= n2) {
s = '1';
n1 = n1 – n2;
}
else
s = '0';
}
return s;
}
function Dig2Dec(s) {
var retV = 0;
if (s.length == 4) {
for (var i = 0; i < 4; i ) {
retV = eval(s.charAt(i)) * Math.pow(2, 3 – i);
}
return retV;
}
return -1;
}
function Hex2Utf8(s) {
var retS = "";
var tempS = "";
var ss = "";
if (s.length == 16) {
tempS = "1110" s.substring(0, 4);
tempS = "10" s.substring(4, 10);
tempS = "10" s.substring(10, 16);
var sss = "0123456789ABCDEF";
for (var i = 0; i < 3; i ) {
retS = "%";
ss = tempS.substring(i * 8, (eval(i) 1) * 8);
retS = sss.charAt(Dig2Dec(ss.substring(0, 4)));
retS = sss.charAt(Dig2Dec(ss.substring(4, 8)));
}
return retS;
}
return "";
}

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

//内部进度,整合数据段
function getBlock(pos,s,d){
var p=pos;
while(len=s[p ]){
for(var i=0;i<len;i )
d.push(s[p i]);
p =len;
}
return p-pos;
}

2、使用形式,当然就是大家的((字符串.UrlEncode() )就足以将字符串调换为utf-8编码的url参数((字符串.UrlEncodeGB2312() )就可把字符串转换到gb2312编码的参数,很好呢,O(∩_∩)O哈哈~

return url;

<HTML>
<HEAD>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<TITLE>Javascript Base64 Demo</TITLE>
<script language=javascript>
/*
* base64编码
*/
var base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 /";
var base64DecodeChars = new Array(
  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63,
  52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1,
  -1, 0, 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, -1, -1, -1, -1, -1,
  -1, 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, -1, -1, -1, -1, -1);
function base64encode(str) {
  var out, i, len;
  var c1, c2, c3;
  len = str.length;
  i = 0;
  out = "";
  while(i < len) {
c1 = str.charCodeAt(i ) & 0xff;
if(i == len)
{
out = base64EncodeChars.charAt(c1 >> 2);
   out = base64EncodeChars.charAt((c1 & 0x3) << 4);
   out = "==";
   break;
}
c2 = str.charCodeAt(i );
if(i == len)
{
   out = base64EncodeChars.charAt(c1 >> 2);
   out = base64EncodeChars.charAt(((c1 & 0x3)<< 4) | ((c2 & 0xF0) >> 4));
   out = base64EncodeChars.charAt((c2 & 0xF) << 2);
   out = "=";
   break;
}
c3 = str.charCodeAt(i );
out = base64EncodeChars.charAt(c1 >> 2);
out = base64EncodeChars.charAt(((c1 & 0x3)<< 4) | ((c2 & 0xF0) >> 4));
out = base64EncodeChars.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >>6));
out = base64EncodeChars.charAt(c3 & 0x3F);
  }
  return out;
}
function base64decode(str) {
  var c1, c2, c3, c4;
  var i, len, out;
  len = str.length;
  i = 0;
  out = "";
  while(i < len) {
/* c1 */
do {
   c1 = base64DecodeChars[str.charCodeAt(i ) & 0xff];
} while(i < len && c1 == -1);
if(c1 == -1)
   break;
/* c2 */
do {
   c2 = base64DecodeChars[str.charCodeAt(i ) & 0xff];
} while(i < len && c2 == -1);
if(c2 == -1)
   break;
out = String.fromCharCode((c1 << 2) | ((c2 & 0x30) >> 4));
/* c3 */
do {
   c3 = str.charCodeAt(i ) & 0xff;
   if(c3 == 61)
  return out;
   c3 = base64DecodeChars[c3];
} while(i < len && c3 == -1);
if(c3 == -1)
   break;
out = String.fromCharCode(((c2 & 0XF) << 4) | ((c3 & 0x3C) >> 2));
/* c4 */
do {
   c4 = str.charCodeAt(i ) & 0xff;
   if(c4 == 61)
  return out;
   c4 = base64DecodeChars[c4];
} while(i < len && c4 == -1);
if(c4 == -1)
   break;
out = String.fromCharCode(((c3 & 0x03) << 6) | c4);
   }
  return out;
}
function utf16to8(str) {
  var out, i, len, c;
  out = "";
  len = str.length;
  for(i = 0; i < len; i ) {
c = str.charCodeAt(i);
if ((c >= 0x0001) && (c <= 0x007F)) {
   out = str.charAt(i);
} else if (c > 0x07FF) {
   out = String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
   out = String.fromCharCode(0x80 | ((c >> 6) & 0x3F));
   out = String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
} else {
   out = String.fromCharCode(0xC0 | ((c >> 6) & 0x1F));
js对图片base64编码字符串进行解码并输出图像示例,实现及应用。   out = String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
}
  }
  return out;
}
js对图片base64编码字符串进行解码并输出图像示例,实现及应用。function utf8to16(str) {
  var out, i, len, c;
  var char2, char3;
  out = "";
  len = str.length;
  i = 0;
  while(i < len) {
c = str.charCodeAt(i );
switch(c >> 4)
{
  case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7:
   // 0xxxxxxx
   out = str.charAt(i-1);
   break;
  case 12: case 13:
   // 110x xxxx  10xx xxxx
   char2 = str.charCodeAt(i );
   out = String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));
   break;
  case 14:
   // 1110 xxxx 10xx xxxx 10xx xxxx
   char2 = str.charCodeAt(i );
   char3 = str.charCodeAt(i );
   out = String.fromCharCode(((c & 0x0F) << 12) |
    ((char2 & 0x3F) << 6) |
    ((char3 & 0x3F) << 0));
   break;
}
}
  return out;
}
/*
* base64编码 End
*/
function doit() {
  var f = document.f
  f.output.value = base64encode(utf16to8(f.source.value))
  f.decode.value = utf8to16(base64decode(f.output.value))
}
</script>
</HEAD>
<BODY>
<H1>Javascript Base64 Demo</H1>
<FORM NAME="f">
原码<BR>
<TEXTAREA NAME="source" ROWS=4 COLS=80 WRAP="soft"></TEXTAREA><BR><BR>
Base64 encode<BR>
<TEXTAREA NAME="output" ROWS=4 COLS=80 WRAP="soft"></TEXTAREA><BR><BR>
Base64 decode<BR>
<TEXTAREA NAME="decode" ROWS=4 COLS=80 WRAP="soft"></TEXTAREA><BR><BR>
<INPUT TYPE=BUTTON VALUE="转换" ONCLICK="doit();">
</FORM>
</BODY>
</html>

DEMO演示

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

打赏扶助笔者写出越来越多好文章,多谢!

打赏小编

//内部进度,获取一帧数额
function getSingleFrame(pos,frame){
var i=pos;
if(bytes[i]==0x21){
i =3;
if(bytes[i]&1)
frame.transparentIndex=bytes[i 3];
frame.delay=bytes[i 1]|(bytes[i 2]<<8);
for(i =5;i<bytes.length&&bytes[i]!=0x2c;i );
if(i==bytes.length){
alert("错误:找不到图像标记符");
return 0;
}
}
frame.offsetX=bytes[i 1]|(bytes[i 2]<<8);
frame.offsetY=bytes[i 3]|(bytes[i 4]<<8);
frame.width=bytes[i 5]|(bytes[i 6]<<8);
frame.height=bytes[i 7]|(bytes[i 8]<<8);
var f=bytes[i 9];
i =10;
if(f&0x40)
frame.interlace=true;
if(f&0x20)
frame.sorted=true;
if(f&0x80){
frame.colorResolution=(f&0x7) 1;
frame.localPalette=[];
i =getPalette(i,bytes,frame.localPalette,1<<frame.colorResolution);
}
else{
frame.colorResolution=gif.colorResolution;
frame.localPalette=gif.globalPalette;
}
var lzwLen=bytes[i ] 1;
i =getBlock(i,bytes,frame.data);
frame.data=decodeLzw(frame.data,lzwLen);
return frame.data?i-pos:0;
}

你也许感兴趣的稿子:

  • js 编码调换 gb2312 和 utf8 互转的2种形式
  • Javascript下的urlencode编码解码方法附decodeUCR-VIComponent
  • js对图纸base64编码字符串举办解码并出口图像示例
  • js 显示base64编码的二进制流网页图片
  • utf-8编码引起js输出中文乱码的化解办法
  • 透过javascript进行UTF-8编码的落到实处况势
  • JS 文字符串调换unicode编码函数
  • JavaScript Base64编码和平解决码,达成URubiconL参数字传送递。
  • JavaScript兑现Base64编码转换
  • js下用gb2312编码解码完结形式
  • JS达成的哈夫曼编码示例【原始版与修改版】

},
bing : function(obj){

你或者感兴趣的小说:

  • JavaScript贯彻Base64编码调换
  • javascript中的Base64、UTF8编码与解码详解
  • javascript从image转变为base61人编码的String
  • js 展现base64编码的二进制流网页图片
  • js对图纸base64编码字符串实行解码并出口图像示例
  • Base64编码加密JS代码网页版
  • JavaScript Base64编码和平解决码,实现UHavalL参数传递。
  • JS在浏览器中深入分析Base64编码图像

打赏协理自己写出更加多好小说,感激!

任选一种支付形式

图片 4 图片 5

2 赞 3 收藏 1 评论

//定义存款和储蓄GIF文件的数据结构
//提供情势showInfo,再次来到图片音信
function GIF(){
this.version=""; //版本号
this.width=0; //逻辑显示器宽度
this.height=0; //逻辑显示屏中度
this.colorResolution=0; //颜色深度
this.sorted=false; //全局色表分类标识
this.globalPalette=null; //全局色表
this.backgroundIndex=-1; //背景象索引
this.pixelAspectRadio=0; //像素宽高比
this.frames=[]; //图像各帧,见GIF_Frame
this.showInfo=function(sep){ //展现图片音信,sep为行分隔符
if(!sep)
sep="n";
var s="Gif infomation:" sep "-------------------";
s =subInfo(this) sep;
for(var i=0;i<this.frames.length;i )
s =sep "frames " i "----------" subInfo(this.frames[i]);
return s;
function subInfo(o){
var s="";
for(var i in o){
if(i=="showInfo"||i=="draw")
continue;
s =sep i ":";
if(typeof(o[i])=="object")
s =(o[i]?o[i].length:"null");
else
s =o[i];
}
return s;
}
}
}

var self = this;

至于小编:Natumsol

图片 6

阿里Baba(Alibaba) 前端程序猿 个人主页 · 笔者的篇章 · 5 ·    

图片 7

//定义存款和储蓄一帧图象的数据结构
//提供格局draw,绘图
function GIF_Frame(){
this.offsetX=0; //X方向偏移量
this.offsetY=0; //Y方向偏移量
this.width=0; //图象宽度
this.height=0; //图象中度
this.localPalette=null; //局地色表
this.colorResolution=0; //颜色深度
this.interlace=false; //交错标识
this.sorted=false; //局地色表分类标记
this.data=[]; //图像数据,存款和储蓄各像素颜色的板寸索引
this.transparentIndex=-1; //透明色索引
this.delay=0; //帧延时
this.draw=function(parent,zoom){
if(!this.data.length)
return;
if(!parent)
parent=document.body;
if(!zoom)
zoom=1;
if(parent.clientWidth<this.width*zoom)
parent.style.width=this.width*zoom;
if(parent.clientHeight<this.height*zoom)
parent.style.height=this.height*zoom;
var id="ImgDefaultDraw";
var img=document.getElementById(id);
if(img)
delete parent.removeChild(img);
img=document.createElement("DIV");
img.id=id;
parent.appendChild(img);
img.style.position="absolute";
var t=document.createElement("DIV");
t.style.overflow="hidden";
t.style.position="absolute";
defLayout(this.data,this.localPalette,this.width,this.height,img,t,zoom);
delete t;
}
}
}

obj.onchange = function(){

//Base64解码
//strIn,输入字符串
//成功重回一个数组,每三个成分包涵一字节消息
//退步重返null
function decodeBase64(strIn){
if(!strIn.length||strIn.length%4)
return null;
var str64=
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 /=";
var index64=[];
for(var i=0;i<str64.length;i )
index64[str64.charAt(i)]=i;
var c0,c1,c2,c3,b0,b1,b2;
var len=strIn.length;
var len1=len;
if(strIn.charAt(len-1)=='=')
len1-=4;
var result=[];
for(var i=0,j=0;i<len1;i =4){
c0=index64[strIn.charAt(i)];
c1=index64[strIn.charAt(i 1)];
c2=index64[strIn.charAt(i 2)];
c3=index64[strIn.charAt(i 3)];
b0=(c0<<2)|(c1>>4);
b1=(c1<<4)|(c2>>2);
b2=(c2<<6)|c3;
result.push(b0&0xff);
result.push(b1&0xff);
result.push(b2&0xff);
}
if(len1!=len){
c0=index64[strIn.charAt(i)];
c1=index64[strIn.charAt(i 1)];
c2=strIn.charAt(i 2);
b0=(c0<<2)|(c1>>4);
result.push(b0&0xff);
if(c2!='='){
c2=index64[c2];
b1=(c1<<4)|(c2>>2);
result.push(b1&0xff);
}
}
return result;
}

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

//用于GIF的LZW解码函数
//arrBytes为源数据,nBits为初阶编码位数
//成功重返数组,各样成分包涵叁个颜料索引
//退步再次来到null
function decodeLzw(arrBytes,nBits){
var cc=1<<(nBits-1);
var eoi=cc 1;
var table=[],mask=[],result=[];
for(var i=0;i<cc;i )
table[i]=(i>>8&0xf).toString(16)
(i>>4&0xf).toString(16) (i&0xf).toString(16);
for(i=2,mask[1]=1;i<13;i )
mask[i]=mask[i-1]<<1|1;
var bc=nBits;
var pos=0,temp=0,tleft=0,code=0,old=0;
while(true){
while(tleft<bc){
temp=temp|(arrBytes[pos ]<<tleft);
tleft =8;
}
code=temp&mask[bc];
tleft-=bc;
temp>>=bc;
if(code==eoi)
break;
if(code==cc){
table.length=cc 2;
bc=nBits;
old=code;
continue;
}
var t="";
if(code<table.length){
t=table[code];
if(old!=cc)
table.push(table[old] t.slice(0,3));
}
else if(old<table.length){
t=table[old] table[old].slice(0,3);
table.push(t);
}
else{
alert("错误:图像数据无效");
return null;
}
old=code;
for(var i=0;i<t.length;i =3)
result.push(parseInt(t.substr(i,3),16))
if(table.length==1<<bc&&bc<12)
bc ;
}
return result;
}

}

//依据字节数组data布局,以最少的div完毕绘图
function defLayout(data,palette,width,height,image,block,zoom){
var map=new Array(height);
for(var i=0;i<height;i ){
map[i]=new Array(width);
for(var j=0;j<width;j )
map[i][j]=data[i*width j];
}
var i,j,i1,i2,j1,j2,c;
for(i=0;i<height;i )
for(j=0;j<width;){
if(map[i][j]==0x100){
j ;
continue;
}
c=map[i][j];
for(i1=i 1;i1<height&&map[i1][j]==c;i1 );
for(j1=j 1;j1<width;j1 ){
for(i2=i;i2<i1&&map[i2][j1]==c;i2 );
if(i2<i1)
break;
}
for(i2=i;i2<i1;i2 )
for(j2=j;j2<j1;j2 )
map[i2][j2]=0x100;
var x=block.cloneNode(true);
x.style.left=j*zoom;
x.style.top=i*zoom;
x.style.width=(j1-j)*zoom;
x.style.height=(i1-i)*zoom;
x.style.backgroundColor=palette[c];
image.appendChild(x);
j=j1;
}
}
</SCRIPT>

},
createImage : function(url){

<script>
function main(){
var t=new Date().getTime();
var xmldom=document.getElementById("imgData");
var gif=getGif("R0lGODlhDwAPAKECAAAAzMzM/////wAAACwAAAAADwAPAAACIISPeQHsrZ5ModrLlN48CXF8m2iQ3YmmKqVlRtW4MLwWACH H09wdGltaXplZCBieSBVbGVhZCBTbWFydFNhdmVyIQAAOw==");
var info=document.getElementById("info");
info.innerHTML=gif.showInfo("<br>");
t=new Date().getTime();
gif.frames[0].draw(document.getElementById("canvas"),1);
info.innerHTML ="<br>绘图耗时" (new Date().get提姆e()-t) "ms";
}
</SCRIPT>
<body onload="main()">
<div id="canvas"></div>
<hr>
<div id="info">页面载入中,请稍候...</div>
</body>
</html>

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

PS:这里再为大家推荐三款在线图片工具供我们参照他事他说加以考查使用

var self = this;

图表调换为Base64编码在线工具:

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

在线Email邮箱Logo制作工具:

},
putImage : function(img){

在线PS图像管理工科具:

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

在线图片格式调换(jpg/bmp/gif/png)工具:

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

ICO图标在线生成工具:

var imgWidth = canvas.width = img.width;

附:别的再引入一款base64编码转变工具

var imgHeight = canvas.height = img.height;

Base64编码解码工具:

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

您也许感兴趣的小说:

  • js 将图纸连接转变到base64格式的简要实例
  • JavaScript将base64图片转变到formData并因此AJAX提交的落实情势
  • Javascript将图纸的相对路线转换为base64编码的措施
  • js 呈现base64编码的二进制流网页图片
  • js达成把图纸的相对路线转为base64字符串、blob对象再上传
  • HTML5 JS压缩图片并赢得图片BASE64编码上传
  • js 图片转base64的方式(两种)
  • JS达成图片调换来base64的种种应用场景实例深入分析

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>

本文由澳门新萄京官方网站发布于澳门新萄京赌场网址,转载请注明出处:js对图片base64编码字符串进行解码并输出图像示例

关键词: