淺談關于PHP解決圖片無損壓縮的問題
更新時間:2017年09月01日 11:15:59 作者:輝客
本篇文章主要介紹了淺談關于PHP解決圖片無損壓縮的問題,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
本文介紹了關于PHP解決圖片無損壓縮的問題,分享給大家,具體如下:
代碼如下:
header("Content-type: image/jpeg");
$file = "111.jpg";
$percent = 1.5; //圖片壓縮比
list($width, $height) = getimagesize($file); //獲取原圖尺寸
//縮放尺寸
$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); //輸出壓縮后的圖片
imagedestroy($dst_im);
imagedestroy($src_im);
我發(fā)現(xiàn)用php的imagecopyresized把大圖片縮成小圖片時,圖片會變得很模糊,這時候要提升清晰度不如用 imagecopyresampled 代替 imagecopyresized也許會更好。
注:壓縮有損失是必然的,看的清楚與否實際上就是是否接受這個范圍的問題.比如你圖像上原圖有些點是2px,但是你壓縮5倍,那么這些點就會消失。
<?php
/**
* desription 壓縮圖片
* @param sting $imgsrc 圖片路徑
* @param string $imgdst 壓縮后保存路徑
*/
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 判斷是否gif動畫
* @param sting $image_file圖片路徑
* @return boolean t 是 f 否
*/
function check_gifcartoon($image_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;
}
?>
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
PHP使用range協(xié)議實現(xiàn)輸出文件斷點續(xù)傳代碼實例
這篇文章主要介紹了PHP使用range協(xié)議實現(xiàn)輸出文件斷點續(xù)傳代碼實例,需要的朋友可以參考下2014-07-07

