Table of Contents
Articles you may be interested in
Home Backend Development PHP Tutorial How to compress JS files into PNG images and store them_PHP tutorial

How to compress JS files into PNG images and store them_PHP tutorial

Jul 13, 2016 am 10:31 AM
js png image storage File compression

Have you ever thought about: in order to compress a js file, convert the js file into a PNG image, and then use the getImageData() function in the canvas control to re-read the image into a js file. I mentioned this method in the article about fast loading of JS files that I published here yesterday. Some netizens are very interested in this method, so I will explain it in detail today.

This can achieve a very high compression ratio. How high it is will be mentioned below. This method uses the canvas control, which also means that it is only valid in browsers that support the canvas control.

How to compress JS files into PNG images and store them_PHP tutorial

Now you can see that the above image looks like a noise image, but it is actually a 30K 8-bit PNG image converted from the 124K prototype frame code (the compression ratio is not bad).

In fact, to convert the code into an image format for storage, it can be converted into GIF and PNG formats. There are 24-bit and 8-bit images in the PNG format. If you use a 24-bit RGB image, each pixel can store 3 bytes of data. If you use an 8-bit RGB image, each pixel can store 1 byte of data.

Testing in PHOTOSHOP found that a 300x100 solid color noise 8-bit image can be compressed to 5K, while the same solid color noise image can only be compressed to 20K if it is a 100x100 24-bit image. If it is an 8-bit GIF image of the same pattern, the compression effect is worse than that of PNG. Therefore, we choose to use 8-bit PNG images as the storage format for compression and decompression.

Now, we need to start compressing the image. Here is how to compress the file written in PHP:

<?php
$filename="http://www.phpernote.com/js/jquery.min.js";
if(file_exists($filename)){
	$iFileSize=filesize($filename);
	$iWidth=ceil(sqrt($iFileSize/1));
	$iHeight=$iWidth;
	$im=imagecreatetruecolor($iWidth,$iHeight);
	$fs=fopen($filename,"r");
	$data=fread($fs,$iFileSize);
	fclose($fs);
	$i=0;
	for($y=0;$y<$iHeight;$y++){
		for($x=0;$x<$iWidth;$x++){
			$ord=ord($data[$i]);
			imagesetpixel($im,$x,$y,imagecolorallocate($im,$ord,$ord,$ord));
			$i++;
		}
	}
	header("Content-Type:image/png");
	imagepng($im);
	imagedestroy($im);
}
Copy after login

It reads the JS file and creates a PNG image. Each pixel in the image is a value between 0-255, and this value corresponds to the ascII value of the JS character.

Of course, in addition to compression, there is also decompression, which is the process of reading images into JS files. This function is written in JS, the specific code is as follows:

function loadPNGData(strFilename,fncCallback){
    var bCanvas=false;  
    var oCanvas=document.createElement("canvas");  
    if(oCanvas.getContext){
        var oCtx=oCanvas.getContext("2d");  
        if(oCtx.getImageData){
            bCanvas=true;  
        }  
    }  
    if(bCanvas){
        var oImg=new Image();  
        oImg.style.position="absolute";  
        oImg.style.left="-10000px";  
        document.body.appendChild(oImg);  
        oImg.onload=function(){
            var iWidth=this.offsetWidth;  
            var iHeight=this.offsetHeight;  
            oCanvas.width=iWidth;  
            oCanvas.height=iHeight;  
            oCanvas.style.width=iWidth+"px";  
            oCanvas.style.height=iHeight+"px";  
            var oText=document.getElementById("output");  
            oCtx.drawImage(this,0,0);  
            var oData=oCtx.getImageData(0,0,iWidth,iHeight).data;  
            var a=[];  
            var len=oData.length;  
            var p=-1;  
            for(var i=0;i<len;i+=4){
                if(oData[i] > 0)  
                    a[++p]=String.fromCharCode(oData[i]);  
            };  
            var strData=a.join("");  
            if(fncCallback){
                fncCallback(strData);  
            }  
            document.body.removeChild(oImg);  
        }  
        oImg.src=strFilename;  
        return true;  
    } else{
        return false;  
    }  
}
Copy after login

Finally, the online test address is given. On this webpage, you can select a PNG image file in the list. Click the load file button to see the image on the webpage. Below the image is the image The read code file.

http://www.nihilogic.dk/labs/canvascompress/

Articles you may be interested in

  • linux chmod (file or file Detailed explanation of command parameters and usage (folder permission setting)
  • php realizes batch compression, packaging and downloading of files
  • php uses ZipArchive function to realize file compression and decompression
  • Smarty temporary files Solution to creation failure
  • PHP method to determine whether remote files exist
  • PHP program to obtain all files in a directory and save the results to an array
  • JS code to obtain keystrokes, How does Js block the user's keystrokes? Js obtains the ASII code corresponding to the user's keystrokes (compatible with all browsers)
  • Js address bar special effects (displays the size of all linked images in the page and the height of the current browser) )

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/764125.htmlTechArticleHave you ever thought about: in order to compress the js file, convert the js file into a PNG image, and then use it in the canvas control The getImageData() function re-reads the image into a js file. I posted here yesterday...
Statement of this Website
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

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)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to compress files to the smallest size with 7-zip? 7-zip usage tutorial How to compress files to the smallest size with 7-zip? 7-zip usage tutorial Mar 14, 2024 am 10:30 AM

How to compress files to the smallest size with 7-zip? 7-zip usage tutorial

Huawei will launch innovative MED storage products next year: rack capacity exceeds 10 PB and power consumption is less than 2 kW Huawei will launch innovative MED storage products next year: rack capacity exceeds 10 PB and power consumption is less than 2 kW Mar 07, 2024 pm 10:43 PM

Huawei will launch innovative MED storage products next year: rack capacity exceeds 10 PB and power consumption is less than 2 kW

Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Dec 17, 2023 pm 06:55 PM

Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Recommended: Excellent JS open source face detection and recognition project

PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts Dec 18, 2023 pm 03:39 PM

PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts

How to create a stock candlestick chart using PHP and JS How to create a stock candlestick chart using PHP and JS Dec 17, 2023 am 08:08 AM

How to create a stock candlestick chart using PHP and JS

Git installation process on Ubuntu Git installation process on Ubuntu Mar 20, 2024 pm 04:51 PM

Git installation process on Ubuntu

How to edit photos on iPhone using iOS 17 How to edit photos on iPhone using iOS 17 Nov 30, 2023 pm 11:39 PM

How to edit photos on iPhone using iOS 17

See all articles