This article mainly introduced the PHP solves the picture lossless compression question, now shares to everybody, also gives everybody to make a reference.
The code is as follows:
Header ("Content-type:image/jpeg"); $file = "111.jpg"; $percent = 1.5; Picture compression ratio list ($width, $height) = getimagesize ($file); Get the original size//scale Size $newwidth = $width * $percent; $newheight = $height * $percent; $src _im = Imagecreatefromjpeg ($file); $DST _im = Imagecreatetruecolor ($newwidth, $newheight); Imagecopyresized ($dst _im, $src _im, 0, 0, 0, 0, $newwidth, $newheight, $width, $height); Imagejpeg ($dst _im); Output compressed picture Imagedestroy ($dst _im); Imagedestroy ($src _im);
I found that using PHP imagecopyresized to shrink the big picture into a small picture, the picture will become very vague, this time to improve the sharpness of the imagecopyresampled instead of imagecopyresized may be better.
Note: Compression has a loss is inevitable, see clearly whether or not to accept this range of problems. For example, your image has some points of 2px, but you compress 5 times times, then these points will disappear.
<?php/** * desription Compressed picture * @param sting $imgsrc Picture path * @param string $IMGDST save path after compression */function Image_png_size_add ($IMGSRC, $IMGDST) {List ($width, $height, $type) =getimagesize ($IMGSRC); $new _width = ($width >600?600: $width) *0.9; $new _height = ($height >600?600: $height) *0.9; Switch ($type) {Case 1: $giftype =check_gifcartoon ($IMGSRC); if ($giftype) {header (' content-type:image/gif '); $image _wp=imagecreatetruecolor ($new _width, $new _height); $image = Imagecreatefromgif ($IMGSRC); Imagecopyresampled ($image _wp, $image, 0, 0, 0, 0, $new _width, $new _height, $width, $height); Imagejpeg ($image _wp, $IMGDST, 75); Imagedestroy ($image _wp); } break; Case 2:header (' content-type:image/jpeg '); $image _wp=imagecreatetruecolor ($new _width, $new _height); $image = Imagecreatefromjpeg ($IMGSRC); Imagecopyresampled ($image _wp, $image, 0, 0, 0, 0, $new _width, $new _height, $width, $height); Imagejpeg ($image _wp, $IMGDST, 75); ImagEdestroy ($image _wp); Break Case 3:header (' content-type:image/png '); $image _wp=imagecreatetruecolor ($new _width, $new _height); $image = Imagecreatefrompng ($IMGSRC); Imagecopyresampled ($image _wp, $image, 0, 0, 0, 0, $new _width, $new _height, $width, $height); Imagejpeg ($image _wp, $IMGDST, 75); Imagedestroy ($image _wp); Break }}/** * desription determine if GIF animation * @param sting $image _file Picture Path * @return Boolean t is f no */function Check_gifcartoon ($im Age_file) {$fp = fopen ($image _file, ' RB '); $image _head = fread ($fp, 1024); Fclose ($FP); Return Preg_match ("/". Chr (0x21). chr (0xff). chr (0x0b). ' NETSCAPE2.0 '. " /", $image _head)? false:true; }?>