ResizeImage.class.php 11.3 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454
<?php
require_once dirname(__FILE__).'/sql/ImageSQL.class.php';
require_once dirname(__FILE__).'/../upload/upload.class.php';
require_once dirname(__FILE__).'/config/config.php';
require_once dirname(__FILE__).'/../image/Image_Core.class.php';
class ResizeImage
{
	/**
	 * 转换图片格式
	 * 
	 * @var $mImageConvertFormat 
	 */
	private $mImageConvertFormat = array('');
	private $mImageSQL = null;
	private $mImageSize = array();
	
	/**
	 * 初始化
	 */
	public function __construct()
	{
		if(class_exists("gmagick"))
		{
			$this->mImageSQL = new ImageSQL();
			$this->mImageConvertFormat = array('.bmp');
			$this->mImageSize = $this->readImageSize();
		}
		else
		{
		   echo 'Gmagick not exists';
		   exit();
		}
	}
	
	/**
	 * 调整所有图片大小
	 * 
	 * @param string $fileMD5
	 * @param int $userID
	 * @param array $imageTypes
	 * @param string $startTime
	 * @param string $endTime
	 * @return boolean
	 */
	public function resizeAllImage($fileMD5='', $userID=0, $imageTypes = array('png','jpg','gif','bmp'),$startTime='', $endTime='')
	{
		//位置,长度
		$startPos = $length = 0;
		while(1)
		{
	
			$startPos += $length;
			$length +=100; 
			//逐步取出数据,返回ID,图片相对路径
			$imagesInfo = $this->mImageSQL->getImageInfo($startPos, $length, $fileMD5, $userID, $imageTypes, $startTime, $endTime);
			//为空时,退出
			if(empty($imagesInfo))
			{
				break;
			}
			else
			{
				//不限制时间
				set_time_limit(0);
				foreach($imagesInfo as $imageInfo)
				{
					//获取物理路径
					$fullImagePath = IMAGE_STORE_ROOT_PATH.$imageInfo[1];
					
					echo " $imageInfo[1]  -->  ";
					$this->imageResize($fullImagePath, true);
					echo "finished!\n";
				}
				if(!empty($fileMD5))
				{
					break;
				}
			}
		}	
		
	}
	
	/**
	 * 读取图片尺寸
	 * 
	 * @return array
	 */
	public function readImageSize()
	{
		$fileName = dirname(__FILE__).IMAGE_SIZE_FILE;
		if(file_exists($fileName))
		{
			//读取配置图片尺寸
			$imageSizeContent = explode("\n",$this->readOver($fileName));
			//返回图片尺寸
			$imageSize = array();
			foreach($imageSizeContent as $size)
			{
				if(!empty($size))
				{
					//获取长宽
					$widthHeight = array_filter(explode('|', $size));
					//长宽要大于0
					if($widthHeight[0]>0 && $widthHeight[1]>0)
					{
						$imageSize[] = array(
								'width' => intval($widthHeight[0]),
								'height' => intval($widthHeight[1])
							);
					}
				}	
			}
			arsort($imageSize);
			return $imageSize;
		}
		else
		{
			return array();
		}
	}
	
	/**
	 * 写入图片尺寸
	 * 
	 * @param int $width
	 * @param int $height
	 * @return boolean
	 */
	public function writeImageSize($width, $height)
	{
		$fileName = dirname(__FILE__).IMAGE_SIZE_FILE;
		if(file_exists($fileName) && is_numeric($width) && is_numeric($height))
		{
			$size = "$width|$height";
			//追加方式
			$this->writeOver($fileName, $size,'a+');
			return true;
		}
		else
		{
			return false;
		}
	}
	
	/**
	 * 读取内容
	 * 
	 * @param string $fileName
	 * @param string $method
	 * @return string
	 */
	private function readOver($fileName,$method="rb")
	{  
    	//由于strpos函数返回是整数值,所以使用!==(不全等)符号判断是否$filename是否包含..,包含则退出显示 
    	strpos($fileName,'..')!==false && exit();  
    	if($handle=@fopen($fileName,$method))
    	{ 
        	//轻便的咨询文件锁定,设置共享锁定   
       	 	flock($handle,LOCK_SH);
       	 	//读取所有内容
        	$filedata=@fread($handle,filesize($fileName));
        	fclose($handle); 
   		 }  
    	//返回文件内容  
   	 	return $filedata;   
	}
	
	/**
	 * 写入内容
	 * 
	 * @param string $fileName
	 * @param string $method
	 * @return boolean
	 */
	private function writeOver($fileName, $content, $method="wb")
	{  
    	//由于strpos函数返回是整数值,所以使用!==(不全等)符号判断是否$filename是否包含..,包含则退出显示 
    	strpos($fileName,'..')!==false && exit();  
    	if($handle=@fopen($fileName,$method))
    	{ 
        	//轻便的咨询文件锁定,设置独占锁定   
       	 	flock($handle,LOCK_EX);
       	 	//写入所有内容
        	fwrite($handle, $content, strlen($content));
        	fclose($handle); 
        	return true;
   		 } 
   		 else
   		 {
   		 	return false;
   		 } 
    	  
	}
	
	/**
	 * 图片调整大小
	 * 
	 * @param string $imagePath
	 * @param boolean $outInfo
	 * @param array $size
	 * {
	 * 		width: int,
	 * 		height: int,
	 * }
	 * @return boolean
	 */
	public function imageResize($imagePath, $outInfo = false, $size = array())
	{
		//获取没有路径的文件名
		$realFile = substr(strrchr($imagePath,'/'),1);
		if(strpos($imagePath,'thumbnail')==false)
		{
			//切图后的路径
    		$cutImagePath = str_replace($realFile,'',$imagePath).'/thumbnail';
		}
		else
		{
			//切图后的路径
			$cutImagePath = str_replace($realFile,'',$imagePath);
		}
    	//创建目录
    	upload::createFolder($cutImagePath);
    	//将要切图的临时文件
    	$prepareCutImagePath = $cutImagePath.'/'.$realFile;
	    if(count($size)>=1)
    	{
    		$this->mImageSize = array($size);
    		if($size['width']==200 && $size['height']==133)
    		{
    			//获取扩展
				$ext = strtolower(strrchr($prepareCutImagePath,'.'));
    			//得到切图后的文件名:用户ID_时间.png =>用户ID_时间_长X宽.png
				$thumbnail = str_replace($ext,'',$prepareCutImagePath).'_'.$size['width'].'X'.$size['height'].$ext;
    			if(file_exists($thumbnail))
				{
    				return false;
				}
    		}
    	}
		foreach($this->mImageSize as $key=> $size)
		{
			if(file_exists($imagePath))
			{
				$image = new Gmagick($imagePath);
				$cs = $image->getimagecolorspace();		
				if ($cs == Gmagick::COLORSPACE_CMYK) 
				{ 
					$image->setImageColorspace(Gmagick::COLORSPACE_SRGB); 
				}
				$image->stripimage();
			}
			else
			{
				continue;
			}	
    		$imageHeight = $image->getimageheight();
			$imageWidth = $image->getimagewidth();
			//剪切宽度
			$resizeWidth = $size['width'];
			//剪切高度
			$resizeHeight = $size['height'];
			//获取扩展
			$ext = strtolower(strrchr($prepareCutImagePath,'.'));
			if(array_search($ext, $this->mImageConvertFormat)!==false)
			{
				//设置格式
				$ext = '.jpg';
			}
			//默认
			if($resizeWidth==200 && $resizeHeight==133)
			{
				//得到切图后的文件名:用户ID_时间.png =>用户ID_时间.png
				$thumbnail = str_replace($ext,'',$prepareCutImagePath).$ext;
			}
			else 
			{
				 //单张图片
				if(count($this->mImageSize)<=2)
				{
                    if(strrpos(strrchr($prepareCutImagePath,'_'),'X'))
					{
				 		//得到切图后的文件名:用户ID_时间.png =>用户ID_时间_长X宽.png
						$thumbnail = str_replace(strrchr($prepareCutImagePath,'_'),'',$prepareCutImagePath).'_'.$resizeWidth.'X'.$resizeHeight.$ext;
					}
					else
					{
					   //得到切图后的文件名:用户ID_时间.png =>用户ID_时间_长X宽.png
						$thumbnail = str_replace(strrchr($prepareCutImagePath,'.'),'',$prepareCutImagePath).'_'.$resizeWidth.'X'.$resizeHeight.$ext;
					}
				}
				else
				{
					//得到切图后的文件名:用户ID_时间.png =>用户ID_时间_长X宽.png
					$thumbnail = str_replace($ext,'',$prepareCutImagePath).'_'.$resizeWidth.'X'.$resizeHeight.$ext;
				}
			}
			//调整长宽相同,并且调整长宽小于实际长宽
			if($resizeWidth==$resizeHeight)
			{
				if(isset($widthSameCutImagePath))
				{
					$imagePath = $widthSameCutImagePath;
					$picinfo = @getimagesize($imagePath);
					$imageWidth = $picinfo[0];
					$imageHeight = $picinfo[1];
				}
				if($resizeHeight<=$imageHeight && $resizeWidth<=$imageWidth)
				{
					$isSameCutFlag = true;
				}
			}
			if(isset($isSameCutFlag)&&$isSameCutFlag)
			{
				//方差
				$variance = 1;
				//累加统计
				$addCount = 0;
				while(1)
				{
					$scaleHeight = $imageHeight / ($resizeHeight*$variance);
					$scaleWidth = $imageWidth / ($resizeWidth*$variance);
					$scale = ($scaleHeight > $scaleWidth)?$scaleHeight:$scaleWidth;
					$finalHeight = $imageHeight/$scale;
					$finalWidth = $imageWidth/$scale;
					if($finalHeight>=$resizeHeight && $finalWidth>=$resizeWidth)
					{
						break;
					}
					//特殊处理
					$addCount++;
					if($addCount>50)
					{
						$finalHeight = $imageHeight;
						$finalWidth = $imageWidth;
						break;
					}
					$variance+=0.04;
				}
				//比例调整
				$finalWidth = floor($finalWidth);
				$finalHeight = floor($finalHeight);
				$left = $top = 0;
				$geometry = array(
								'width'=>$resizeWidth,
								'height'=>$resizeHeight,
								'top'=>'center',
								'left'=>'center',
							);
				$newGeometry = $this->sanitize_geometry($finalWidth, $finalHeight, $geometry);
                //切割
                $image->resizeimage($finalWidth, $finalHeight, null, 1);
				if(isset($newGeometry['left']) && isset($newGeometry['top']))
                {
                    $left = $newGeometry['left'];
                    $top = $newGeometry['top'];
                }
				$image->cropimage($resizeWidth, $resizeHeight, $left, $top);
				$image->writeimage(str_replace('//','/',$thumbnail));
				//大于200K
				/*if((filesize($thumbnail)/1000)>200)
				{
				
				
				}*/
				unset($image);
				//不切割
				$isSameCutFlag = false;
			}
			else
			{
				if($imageHeight <= $resizeHeight && $imageWidth <= $resizeWidth)
				{
					$finalHeight = $imageHeight;
					$finalWidth = $imageWidth;
				}
				else    //等比缩放
				{
					$scaleHeight = $imageHeight / $resizeHeight;
					$scaleWidth = $imageWidth / $resizeWidth;
					$scale = ($scaleHeight > $scaleWidth)?$scaleHeight:$scaleWidth;
					$finalHeight = ceil($imageHeight/$scale);
					$finalWidth = ceil($imageWidth/$scale);
					if($finalWidth<=0)
					{
						$finalWidth = $imageWidth;
					}
					if($finalHeight<=0)
					{
						$finalHeight = $imageHeight;
					}
				}	
				$image->resizeimage($finalWidth, $finalHeight, null, 1);
				$image->writeimage(str_replace('//','/',$thumbnail));	
				//切除上一次图	
				$imagePath = $thumbnail;
				unset($image);
				unset($newGeometry);
				unset($geometry);
			}
			if($key == 0)
			{
				//保存相同高宽尺寸要的大图
				$widthSameCutImagePath = $imagePath;
			}
			if($outInfo)
			{
				echo " $resizeWidth*$resizeHeight, ";
			}	
		}

		if(isset($key))
		{
			return true;
		}	
	}
	
	private function sanitize_geometry($imageWidth, $imageHeight, $geometry)
	{
		$geometry['width']  = min($geometry['width'], $imageWidth);
		$geometry['height'] = min($geometry['height'], $imageHeight);
        $resize = array(
                             'top'=>0,
                             'left'=>0
                        );
		// Set standard coordinates if given, otherwise use pixel values
		if ($geometry['top'] === 'center')
		{
			$resize['top'] = floor(($imageHeight / 2) - ($geometry['height'] / 2));
		}
		elseif ($geometry['top'] === 'top')
		{
			$resize['top'] = 0;
		}
		elseif ($geometry['top'] === 'bottom')
		{
			$resize['top'] = $imageHeight - $geometry['height'];
		}

		// Set standard coordinates if given, otherwise use pixel values
		if ($geometry['left'] === 'center')
		{
			$resize['left'] = floor(($imageWidth / 2) - ($geometry['width'] / 2));
		}
		elseif ($geometry['left'] === 'left')
		{
			$resize['left'] = 0;
		}
		elseif ($geometry['left'] === 'right')
		{
			$resize['left'] = $imageWidth - $geometry['height'];
		}
		return $resize;
	}
}