search
HomeWeb Front-endJS Tutorialjs decodes the image base64 encoded string and outputs the image example_javascript skills

Copy code The code is as follows:







/////////////////////////////
//base64 encoded GIF image decoding
//By Mozart0
//2005/10/29
////////////////////

//Create a GIF class object
/ /Class GIF is defined inside this function
// str64: Base64 encoded string of gif file
// Returns the created GIF object on success
// Returns null on failure
function getGif(str64){
var bytes=decodeBase64(str64);
if(!bytes){
alert("Error: Invalid Base64 encoding");
return null;
}
var gif =new GIF();
for(var i=0;igif.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]gif.height=bytes[i 2]|(bytes[i 3]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}
i =7;
for(var j=i;jif(bytes[j]==0x21&&bytes[j 1]==0xf9)
break;
if(j==bytes.length){
for(;iif(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;iif(bytes[i]==0x21&&bytes[i 1]==0xf9)
break;
}
while(i}
return gif;

//Internal process, generate color table
function getPalette(pos,s,d,len) {
len*=3;
for(var i=pos;id.push('#' (s[i] (s[i 1] (s [i 2]return len;
}

//Internal process, integration Data segment
function getBlock(pos,s,d){
var p=pos;
while(len=s[p]){
for(var i=0;id.push(s[p i]);
p =len;
}
return p-pos;
}

//Internal process, get One 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]for(i = 5;iif(i==bytes.length){
alert("Error: Image identifier not found");
return 0;
}
}
frame.offsetX=bytes[i 1]|(bytes[i 2]frame.offsetY=bytes[i 3]| (bytes[i 4]frame.width=bytes[i 5]|(bytes[i 6]frame.height=bytes[i 7 ]|(bytes[i 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
//Provide method showInfo and 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 classification flag
this.globalPalette=null; //Global color table
this.backgroundIndex=-1; //Background Color index
this.pixelAspectRadio=0; //Pixel aspect ratio
this.frames=[]; //For each frame of the image, see GIF_Frame
this.showInfo=function(sep){ //Display Image information, sep is the line separator
if(!sep)
sep="n";
var s="Gif infomation:" sep "------------ -------";
s =subInfo(this) sep;
for(var i=0;is =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 to store a frame of image
//Provide method draw, drawing
function GIF_Frame (){
this.offsetX=0; //X-direction offset
this.offsetY=0; //Y-direction offset
this.width=0; //Image width
this.height=0; //Image height
this.localPalette=null; //Local color table
this.colorResolution=0; //Color depth
this.interlace=false; / /Interlaced flag
this.sorted=false; //Local color table classification flag
this.data=[]; //Image data, storing the integer index of each pixel color
this.transparentIndex=-1 ; //Transparent color index
this.delay=0; //Frame delay
this.draw=function(parent,zoom){
if(!this.data.length)
return ;
if(!parent)
parent=document.body;
if(!zoom)
zoom=1;
if(parent.clientWidthparent.style.width=this.width*zoom;
if(parent.clientHeightparent.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;
}
}
}

//Base64 decoding
//strIn, input string
//returns an array successfully, each element Contains one byte of information
// Returns null on failure
function decodeBase64(strIn){
if(!strIn.length||strIn.length%4)
return null;
var str64 =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 /=";
var index64=[];
for(var i=0;iindex64[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>4);
b1=(c1>2 );
b2=(c2result.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>4);
result.push(b0&0xff);
if(c2!='='){
c2=index64[c2];
b1=(c1>2);
result.push(b1&0xff);
}
}
return result;
}

//LZW decoding function for GIF
//arrBytes is the source data, nBits is the initial encoding number of bits
//Successfully returns the array, each Elements include a color index
// Returns null on failure
function decodeLzw(arrBytes,nBits){
var cc=1var eoi=cc 1;
var table=[],mask=[],result=[];
for(var i=0;itable[i]=(i>>8&0xf) .toString(16)
(i>>4&0xf).toString(16) (i&0xf).toString(16);
for(i=2,mask[1]=1;imask[i]=mask[i-1]var bc=nBits;
var pos=0,temp=0,tleft=0,code=0 ,old=0;
while(true){
while(tlefttemp=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(codet=table[code];
if(old!=cc)
table.push(table[old] t.slice(0,3) );
}
else if(oldt=table[old] table[old].slice(0,3);
table.push(t);
}
else{
alert("Error: Invalid image data");
return null;
}
old=code;
for(var i=0; iresult.push(parseInt(t.substr(i,3),16))
if(table.length==1bc ;
}
return result;
}

//According to the byte array data layout, complete the drawing with the least number of divs
function defLayout(data,palette,width ,height,image,block,zoom){
var map=new Array(height);
for(var i=0;imap[i]=new Array( width);
for(var j=0;jmap[i][j]=data[i*width j];
}
var i,j, i1,i2,j1,j2,c;
for(i=0;ifor(j=0;jif(map[i][ j]==0x100){
j ;
continue;
}
c=map[i][j];
for(i1=i 1;i1for(j1=j 1;j1for(i2=i;i2if(i2break;
}
for(i2=i;i2for(j2=j;j2map[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> <BR>function main(){ <BR>var t=new Date().getTime(); <BR>var xmldom=document.getElementById("imgData"); <BR>var gif=getGif("R0lGODlhDwAPAKECAAAAzMzM/////wAAACwAAAAADwAPAAACIISPeQHsrZ5ModrLlN48CXF8m2iQ3YmmKqVlRtW4MLwWACH H09wdGltaXplZCBieSBVbGVhZCBTbWFydFNhdmVyIQAAOw=="); <BR>var info=document.getElementById("info"); <BR>info.innerHTML=gif.showInfo("<br>"); <BR>t=new Date().getTime(); <BR>gif.frames[0].draw(document.getElementById("canvas"),1); <BR>info.innerHTML ="<br>缁</script>
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor