Js decodes the base64 encoded string of the image and outputs the image example _ javascript skills

Source: Internet
Author: User
This article describes how to decode the base64 encoded string of an image and output the image in Javascript. You can refer to the following example. The Code is as follows:







Script
///////////////////////////
// Base64 encoded GIF image decoding
// By sort art0
// 2005/10/29
////////////////////

// Create a GIF object
// Class GIF defined in this function
// Str64: Base64 encoded string of the gif File
// The created GIF object is returned.
// If a failure occurs, null is returned.
Function getGif (str64 ){
Var bytes = decodeBase64 (str64 );
If (! Bytes ){
Alert ("error: invalid Base64 encoding ");
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 ("error: Non-Gif image format ");
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 If (bytes [j] = 0x21 & bytes [j + 1] = 0xf9)
Break;
If (j = bytes. length ){
For (; I If (bytes [I] = 0x2c)
Break;
If (I = bytes. length ){
Alert ("error: Image Data not found ");
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 If (bytes [I] = 0x21 & bytes [I + 1] = 0xf9)
Break;
}
While (I }
Return gif;

// Internal process, color table
Function getPalette (pos, s, d, len ){
Len * = 3;
For (var I = pos; I 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;
}

// Internal process, integrating data segments
Function getBlock (pos, s, d ){
Var p = pos;
While (len = s [p ++]) {
For (var I = 0; I D. push (s [p + I]);
P + = len;
}
Return p-pos;
}

// Internal process to obtain a frame of data
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 If (I = bytes. length ){
Alert ("error: Image flag not found ");
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 < }
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;
}

// Define the data structure for storing GIF files
// Provides the showInfo method to return image information.
Function GIF (){
This. version = ""; // version number
This. width = 0; // logical screen width
This. height = 0; // logical screen height
This. colorResolution = 0; // color depth
This. sorted = false; // global color table category mark
This. globalPalette = null; // global color table
This. backgroundIndex =-1; // background color index
This. pixelAspectRadio = 0; // pixel aspect ratio
This. frames = []; // image frames, see GIF_Frame
This. showInfo = function (sep) {// display the image information, and sep is the line separator.
If (! Sep)
Sep = "\ n ";
Var s = "Gif infomation:" + sep + "-------------------";
S + = subInfo (this) + sep;
For (var I = 0; 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;
}
}
}

// Define the data structure for storing an image
// Provides the draw and drawing methods.
Function GIF_Frame (){
This. offsetX = 0; // offset in the X direction
This. offsetY = 0; // offset in the Y direction
This. width = 0; // Image width
This. height = 0; // Image height
This. localPalette = null; // partial color table
This. colorResolution = 0; // color depth
This. interlace = false; // staggered flag
This. sorted = false; // classification mark of the partial color table
This. data = []; // image data, storing integer indexes of each pixel color
This. transparentIndex =-1; // transparent Index
This. delay = 0; // frame latency
This. draw = function (parent, zoom ){
If (! This. data. length)
Return;
If (! Parent)
Parent = document. body;
If (! Zoom)
Zoom = 1;
If (parent. clientWidth Parent. style. width = this. width * zoom;
If (parent. clientHeight Parent. style. height = this. height * zoom;
Var id = "imgdefadradraw ";
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;
}
}
}

// Base64 Decoding
// StrIn, input string
// An array is returned successfully. Each element contains one byte of information.
// If a failure occurs, null is returned.
Function decodeBase64 (strIn ){
If (! StrIn. length | strIn. length % 4)
Return null;
Var str64 =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 +/= ";
Var index64 = [];
For (var I = 0; 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 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;
}

// LZW decoding function for GIF
// ArrBytes is the source data, and nBits is the initial encoding bit.
// An array is returned successfully. Each element includes a color index.
// If a failure occurs, null is returned.
Function decodeLzw (arrBytes, nBits ){
Var cc = 1 <(nBits-1 );
Var eoi = cc + 1;
Var table = [], mask = [], result = [];
For (var I = 0; 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 Temp = temp | (arrBytes [pos ++] < 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 T = table [code];
If (old! = Cc)
Table. push (table [old] + t. slice (0, 3 ));
}
Else if (old T = table [old] + table [old]. slice (0, 3 );
Table. push (t );
}
Else {
Alert ("error: Invalid image data ");
Return null;
}
Old = code;
For (var I = 0; I Result. push (parseInt (t. substr (I, 3), 16 ))
If (table. length = 1 < Bc ++;
}
Return result;
}

// Plot with minimum p Based on the data Layout of the byte array
Function defLayout (data, palette, width, height, image, block, zoom ){
Var map = new Array (height );
For (var I = 0; I Map [I] = new Array (width );
For (var j = 0; j Map [I] [j] = data [I * width + j];
}
Var I, j, i1, i2, j1, j2, c;
For (I = 0; I For (j = 0; j If (map [I] [j] = 0x100 ){
J ++;
Continue;
}
C = map [I] [j];
For (i1 = I + 1; i1 For (j1 = j + 1; j1 For (i2 = I; i2 If (i2 Break;
}
For (i2 = I; i2 For (j2 = j; 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

Script
Function main (){
Var t = new Date (). getTime ();
Var xmldom = document. getElementById ("imgData ");
Var gif = getGif ("R0lGODlhDwAPAKECAAAAzMzM // merged + h09wdgltaxplzcbiesbvbgvhzcbwfydfnhdmvyiqaaow = ");
Var info = document. getElementById ("info ");
Info. innerHTML = gif. showInfo ("
");
T = new Date (). getTime ();
Gif. frames [0]. draw (document. getElementById ("canvas"), 1 );
Info. innerHTML + ="
Drawing time consumption "+ (new Date (). getTime ()-t) +" ms ";
}
SCRIPT



Loading the page. Please wait...



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.