PHP壓縮圖片函數

WBOY
發布: 2016-07-28 08:28:11
原創
1334 人瀏覽過
/** 图片压缩函数
 * @param $orgin_file 原始图片文件
 * @param $maxwidth 最大宽度
 * @param $maxheight 最大高度
 * @param $name 压缩图片名
 * @param $filetype 图片类型
 */
function resizeImage($orgin_file,$maxwidth,$maxheight,$name,$filetype)
{
	$im = '';
	switch ($filetype){
		case '.jpg':
			$im=imagecreatefromjpeg($orgin_file);
			break;
		case '.png':
			$im=imagecreatefrompng($orgin_file);
			break;
		case '.gif':
			$im=imagecreatefromgif($orgin_file);
			break;
		default:
			$im=imagecreatefromgd($orgin_file);
	}
	$pic_width = imagesx($im);
	$pic_height = imagesy($im);

	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);//PHP系统函数
			imagecopyresampled($newim,$im,0,0,0,0,$newwidth,$newheight,$pic_width,$pic_height);//PHP系统函数
		}
		else
		{
			$newim = imagecreate($newwidth,$newheight);
			imagecopyresized($newim,$im,0,0,0,0,$newwidth,$newheight,$pic_width,$pic_height);
		}

		$name = $name.$filetype;
		switch ($filetype){
			case '.jpg':
				imagejpeg($newim,$name);
				break;
			case '.png':
				imagepng($newim,$name);
				break;
			case '.gif':
				imagegif($newim,$name);
				break;
			default:
				imagegd($newim,$name);
		}

		imagedestroy($newim);
	}
	else
	{
		$name = $name.$filetype;
		switch ($filetype){
			case '.jpg':
				imagejpeg($im,$name);
				break;
			case '.png':
				imagepng($im,$name);
				break;
			case '.gif':
				imagegif($im,$name);
				break;
			default:
				imagegd($im,$name);
		}
	}
}
登入後複製
圖片新增浮水印可以參考「imagecopymerge」函數,手冊很詳細。

以上就介紹了 PHP壓縮圖片函數,包含了方面的內容,希望對PHP教學有興趣的朋友有幫助。

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!