<?php
/**
* 内容中的大图替换成缩略图 
*
*/
$th= new thumbimg();
$th->index();
class thumbimg {
	public $dir="tempimg/";
	public function __construct(){

	}
	public function index(){
		$url=isset($_GET['url'])?$_GET['url']:false;
		if($url){
			$dir=$this->dir;
			$width=isset($_GET['width'])?$_GET['width']:100;
			$height=isset($_GET['height'])?$_GET['height']:100;
			$is_all=isset($_GET['all'])?$_GET['all']:true;
			$md5=md5($url);
			$dir.=$md5{0}."/".$md5{1}."/".$md5{2}."/";
			$this->umkdir($dir);
			$newurl=$dir.basename($url);
			if(file_exists($newurl)){
				header("Content-type:image/jpeg;");
				echo file_get_contents($newurl);
				exit;
			}else{
				ob_start();
				header("Content-type:image/jpeg;");			
				$this->makethumb($url,$width,$height,$is_all);
				$content=ob_get_contents();
				ob_end_clean();
				header("Content-type:image/jpeg;");
				file_put_contents($newurl,$content);
				echo $content;
				exit;
			}
		}
	}
	
	/**
	缩略图函数
	*/
	function makethumb($img,$dstw,$dsth=999,$all=false)
	{
		$get_size=getimagesize($img);
		list($width,$height) =  $get_size;
		if($width<5) return false;
		$percent=$dstw/$width;//固定宽度
		$new_width = $width * $percent;
		$new_height = $height * $percent;
		if($all){
			$new_width=$dstw;
			$new_height=$dsth;
			if($height>$width){
				$height=$width;
			}else{
				$width=$height;
			}
		}
		$im = imagecreatetruecolor($new_width, $new_height);
		$imgtype=$this->getimgtype($get_size['mime']);
		$image = $this->imagecreatefrom($img,$imgtype);
		
		imagecopyresampled($im, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
		
		$this->imagesave($im,$imgtype);
		return $dstimg;
	}
	
	//获取图片后缀
	function getimgtype($mime)
	{
		switch($mime)
		{
				case 'image/gif':
				return 'gif';
				break;
				case 'image/bmp':
				case "image/x-ms-bmp":
				return 'bmp';
				break;
				case "image/jpeg":
				return 'jpg';
				break;
				case 'image/png':
				return 'png';
				break;
				default:
				return '';
			}
	}
	
	
	//输出图像
	function imagesave($im,$imgtype='jpeg')
	{
		switch($imgtype)
		{
			case "gif":
					imagegif($im);
					break;	
			case "jpg":
					imagejpeg($im,NULL,100);
					break;
			case "png":
					imagepng($im);
					break;
			case "bmp":
					imagewbmp($im);
					break;
					
		}
	}
	
	function imagecreatefrom($img,$imgtype)
	{
		switch($imgtype)
		{
			case 'gif':
				return imagecreatefromgif($img);
			break;
			case "jpg":
				return imagecreatefromjpeg($img);
			break;
			case "png":
				return imagecreatefrompng($img);
			break;
			case 'bmp':
				return imagecreatefromwbmp($img);
			break;
		}
	}
	
	function umkdir($dir)
	{
		if(!defined("ROOT_PATH")){
			define("ROOT_PATH","");
		}
		$dir=str_replace(ROOT_PATH,"",$dir);
		$arr=explode("/",$dir);
		foreach($arr as $key=>$val)
		{
			$d="";
			for($i=0;$i<=$key;$i++)
			{
				$d.=$arr[$i]."/";
			} 
			if(!file_exists(ROOT_PATH.$d))
			{ 
				mkdir(ROOT_PATH.$d,0755);
			}
		}
	}
	
}

?>