本文實(shí)例為大家分享了PHP實(shí)現(xiàn)圖片壓縮的具體代碼,供大家參考,具體內(nèi)容如下
/** * 生成圖片 * @param string $im 源圖片路徑 * @param string $dest 目標(biāo)圖片路徑 * @param int $maxwidth 生成圖片寬 * @param int $maxheight 生成圖片高 */ function resizeImage($im, $dest, $maxwidth, $maxheight) { $img = getimagesize($im); switch ($img[2]) { case 1: $im = @imagecreatefromgif($im); break; case 2: $im = @imagecreatefromjpeg($im); break; case 3: $im = @imagecreatefrompng($im); break; } $pic_width = imagesx($im); $pic_height = imagesy($im); $resizewidth_tag = false; $resizeheight_tag = false; if (($maxwidth $pic_width > $maxwidth) || ($maxheight $pic_height > $maxheight)) { if ($maxwidth $pic_width > $maxwidth) { $widthratio = $maxwidth / $pic_width; $resizewidth_tag = true; } if ($maxheight $pic_height > $maxheight) { $heightratio = $maxheight / $pic_height; $resizeheight_tag = true; } if ($resizewidth_tag $resizeheight_tag) { if ($widthratio $heightratio) $ratio = $widthratio; else $ratio = $heightratio; } if ($resizewidth_tag !$resizeheight_tag) $ratio = $widthratio; if ($resizeheight_tag !$resizewidth_tag) $ratio = $heightratio; $newwidth = $pic_width * $ratio; $newheight = $pic_height * $ratio; if (function_exists("imagecopyresampled")) { $newim = imagecreatetruecolor($newwidth, $newheight); imagecopyresampled($newim, $im, 0, 0, 0, 0, $newwidth, $newheight, $pic_width, $pic_height); } else { $newim = imagecreate($newwidth, $newheight); imagecopyresized($newim, $im, 0, 0, 0, 0, $newwidth, $newheight, $pic_width, $pic_height); } imagejpeg($newim, $dest); imagedestroy($newim); } else { imagejpeg($im, $dest); } } /** * 圖片壓縮處理 * @param string $sFile 源圖片路徑 * @param int $iWidth 自定義圖片寬度 * @param int $iHeight 自定義圖片高度 * @return string 壓縮后的圖片路徑 */ function getThumb($sFile,$iWidth,$iHeight){ //圖片公共路徑 $public_path = ''; //判斷該圖片是否存在 if(!file_exists($public_path.$sFile)) return $sFile; //判斷圖片格式(圖片文件后綴) $extend = explode("." , $sFile); $attach_fileext = strtolower($extend[count($extend) - 1]); if (!in_array($attach_fileext, array('jpg','png','jpeg'))){ return ''; } //壓縮圖片文件名稱(chēng) $sFileNameS = str_replace(".".$attach_fileext, "_".$iWidth.'_'.$iHeight.'.'.$attach_fileext, $sFile); //判斷是否已壓縮圖片,若是則返回壓縮圖片路徑 if(file_exists($public_path.$sFileNameS)){ return $sFileNameS; } //生成壓縮圖片,并存儲(chǔ)到原圖同路徑下 resizeImage($public_path.$sFile, $public_path.$sFileNameS, $iWidth, $iHeight); if(!file_exists($public_path.$sFileNameS)){ return $sFile; } return $sFileNameS; }
使用實(shí)例:
//原圖 img/img.jpg //生成壓縮圖 img/img_300_300.jpg getThumb('img/img.jpg',300,300);
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家,關(guān)注腳本之家公眾號(hào)的更多精彩內(nèi)容。
標(biāo)簽:太原 辛集 鄂州 白銀 崇左 廊坊 衡陽(yáng) 綏化
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《PHP實(shí)現(xiàn)圖片壓縮》,本文關(guān)鍵詞 PHP,實(shí)現(xiàn),圖片,壓縮,PHP,實(shí)現(xiàn),;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問(wèn)題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無(wú)關(guān)。