Images.class.php 12.4 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
<?php

class Lib_Images
{
	/**
	 * 获取七牛尺寸
	 *
	 * @param string $size
	 * @return string
	 */
	public static function getExistQiniuSize($size)
	{
		$qiniuKey = 'mem_qiniu_sizes';
		$sizes = Lib_Utils_Cache_Data::get($qiniuKey);
		if(empty($sizes))
		{
			$sizes = array(57600 =>'0240x0240', 102400 =>'0320x0320', 230400 =>'0480x0480',409600 => '0640x0640',
					5999400=>'0600x9999',3600 =>'0060x0060', 85264=>'0292x0292',79920=>'0296x0270',42632=>'0292x0146',
					21316=>'0146x0146', 30976 => '0176x0176',16936 =>'0146x0116',586240=>'0640x0916', 473600=>'0640x0740',10000 => '0100x0100', 
					22500 =>'0150x0150',14400 => '0120x0120',5399460=>'0540x9999',900=>'0030x0030');
			asort($sizes);
			Lib_Utils_Cache_Data::set($qiniuKey, $sizes);
		}
		$sizeKey = 'qiniu_sizes_'.$size;
		$key = Lib_Utils_Cache_Data::get($sizeKey);
		if(empty($key))
		{
			$key = array_search($size, $sizes);
			if($key === false)
			{
				//获取接近的尺寸
				$arr = explode('x', $size);
				$pixel = intval($arr[0]) * intval($arr[1]);
				foreach($sizes as $keyPixel => $size)
				{
					if($keyPixel > $pixel)
					{
						$key = $keyPixel;
						break;
					}
				}
				//都不存在,获取第一个
				if($key === false)
				{
					$key = current($sizes);
				}
			}
			Lib_Utils_Cache_Data::set($sizeKey, $key);
		}
		return $sizes[$key];
	}
	
	/**
	 * 保存图片
	 *
	 * @param mixed $file (文件或文件流)
	 * @param string $project (项目名称,默认为fragmentimg)
	 * @param boolean $preProcess (控制是否预先处理图片) @since 1.2.3
	 * @return string (返回相对图片路径)
	 */
	public static function saveImage($file, $project = 'fragmentimg', $preProcess = false)
	{
		if (!isset(Config_File_Upload::${$project}))
		{
			return '';
		}
		$_key_data = Config_File_Upload::${$project};
		$projectConfig = self::genConfig($project);
		if (is_array($file))
		{
			$up = new Util_Upload_File($file, $projectConfig['serverPath']);
			$key = key($file);
		}
		elseif (@file_exists($file) && is_file($file))//文件
		{
			$up = new Util_Upload_FileStream(@file_get_contents($file), $projectConfig['serverPath']);
			$key = 0;
		}
		// 2014/01/07 hf: 修改抓取外网图片抓不了的问题
		elseif (is_string($file) && isset($file[0]))
		{
			$up = new Util_Upload_FileStream($file, $projectConfig['serverPath']);
			$key = 0;
			$file = null;
		}
		else
		{
			return '';
		}
		$up->setFormat($projectConfig['format']);
		$up->setMaxFileSize($projectConfig['upload_max_size']);
		$up->setPrefix($projectConfig['randNode']);
		if (isset($_key_data['file_path']))
		{
			$up->setNewFileName($_key_data['file_path']);
		}
		$checkStatus = $up->check();
		if ($checkStatus['code'] == 0)
		{
			$checkStatus = $up->write();
		}
		$imagePath = isset($checkStatus['result']['hit'][$key]['relaPath']) ? $checkStatus['result']['hit'][$key]['relaPath'] : '';
		return $imagePath;
	}
	
    /**
     * 获取图片地址
     * 
     * @param string $url 图片的相对地址
     * @param string $type 图片的类型
     * @param string $project 图片模块分类名
     * @param string $crop 切图方式
     * @param string $platform 默认:web
     * @return string
     */
    public static function getImageUrl($url = '', $type = null, $project = null, $crop = 'customCrop', $platform = 'web')
    {
    	$qiniuUploadState = defined('QINIU_UPLOAD_STATE') ? QINIU_UPLOAD_STATE : false;
        // 判断图片地址的有效性
        if ($url === null || $url === '' || $url === 'boy' || $url === 'girl' || ! is_string($url))
        {
            // 地址: 新社区用户默认头像
            if ($project === 'headimg')
            {   
                $finds = ($url === 'girl') ? Config_Static::$headImgGirl : Config_Static::$headImgBoy;
                if (! array_key_exists($type, $finds))
            	{
            		$type = key($finds);
            	}
                return SITE_IMG . $finds[$type];
            }
            return '';
        }
		
		// 地址: 站内站外的绝对地址
		if (0 === strpos($url, 'http://') || 0 === strpos($url, 'https://')) 
		{  
		    if (($host = parse_url($url)) && isset($host['host'])) 
		    {
			    return $url;
		    }
		}
		
		// 地址: 老社区的图片
		if (0 === strpos($url, OLD_SITE_MAIN_I) || 0 === strpos($url, OLD_SITE_MAIN_P) || 0 === strpos($url, 'yohobuy.com'))
		{
		    return $url;
		}
		
		// 地址: 老社区用户的头像或用户相册的照片
		if (0 === stripos($url, '/user/') || 0 === stripos($url, '/photo/'))
		{
		    return OLD_SITE_MAIN . $url;
		}
		
		// 判断项目是否存在
		if (true !== property_exists('Config_File_Upload', $project))
		{
			return '';
		}
		
		//  获取服务器域名
		$imageInfo = pathinfo($url);
		$sysKey = self::getSysKey($imageInfo['basename']);
	    if (array_key_exists($sysKey, Config_File_Image::$imageServerUrl))
	    {
    		$sourceUrl = Config_File_Image::$imageServerUrl[$sysKey];
    		$targetUrl = Config_File_Image::$imageThumbUrl[$sysKey];
	    }
	    else 
	    {
	        return '';
	    }
	    
	    $imageConfig = Config_File_Upload::${$project};
		
	    // 判断是否访问源图片文件
		if ($type == 'source') 
		{
		    $sourceUrl .= $imageConfig['path'] . $url;
		    if($qiniuUploadState && $platform != 'web')//七牛,移动版
		    {
		    	$sourceUrl = sprintf("%s_.%s", $sourceUrl, $imageInfo['extension']);
		    }
		    // 返回图片源地址
		    return $sourceUrl;
		} 
		// 格式化尺寸为"0000x0000"格式
		if (is_string($type) && strpos($type, 'x') !== false)
		{
			$finds = explode('x', $type);
			$type = str_pad($finds[0], 4, '0', STR_PAD_LEFT) . 'x' . str_pad($finds[1], 4, '0', STR_PAD_LEFT);
		}
		$finds = Config_Static::$cropTypes;
		if (! array_key_exists($crop, $finds))
		{
			$crop = key($finds);
		}
		// 缩略剪切方式
		if($qiniuUploadState)//七牛
		{
			if($platform != 'web')//移动版
			{
				$finds = Config_Static::$qiniuCropTypes;
				$type = self::getExistQiniuSize($type);
				//_-宽x高-切图方式.图片后缀
				$rule = '_-' . $type . '-' . $finds[$crop] . '.' . $imageInfo['extension'];
			}
			else
			{
				//网页版使用参数规则
				$rule = str_replace('{size}', $type, Config_Static::$qiniuCropRules[$crop]);
			}
		}
		else //原始版
		{
			//-宽x高-切图方式.图片后缀
			$rule = '-' . $type . '-' . $finds[$crop] . '.' . $imageInfo['extension'];
		}
		if($qiniuUploadState)
		{
			//域名/项目名/年/月/日/时/{01|02}md5(32).图片后缀[_-宽x高-切图方式.图片后缀|?imageMogr2/thumbnail/xx/xxx]
			$targetUrl .= $imageConfig['path'] . $imageInfo['dirname'] . '/' . basename($url, '.' . $imageInfo['extension']) . '.' . $imageInfo['extension'].$rule;
		}
		else 
		{
			// 生成路径的格式: "域名/项目名/年/月/日/时/{01|02}md5(32)-宽x高-切图方式.图片后缀"
			$targetUrl .= $imageConfig['path'] . $imageInfo['dirname'] . '/' . basename($url, '.' . $imageInfo['extension']) . $rule;
		}
		// 返回缩略图地址
		return $targetUrl;
	}
	
	/**
	 * 预处理图片
	 *
	 * @param string $imagePath (源图片相对路径)
	 * @param array $project (项目)
	 * @param array $projectConfig (项目配置)
	 * @param array $data (图片的信息)
	 * @return void
	 */
	public static function processImage($imagePath, $project, &$projectConfig, &$data)
	{
		return self::getImageInfo($imagePath, $project);
	}
	
	/**
	 * 获取图片的信息
	 * 
     * @param string $url (文件存放地址)
     * @param string $project (文件项目名)
     * @return false | array(
     *     width => 宽度,
     *     height => 高度,
     *     size => 大小,
     *     mine => 'MINE'
     * )
     * 
     * @example 
     * Lib_Images::getImageInfo('/2013/03/06/17/019182a667143d313a18b16e4525235b4d.jpg', 'blogimg');
     * Lib_Images::getImageInfo('http://img03.res.yoho.cn/blogimg/2012/09/18/11/01167a11b8e7c0d913e789d75b2e52f433-0580x320-1.jpeg', 'blogimg');
	 */
	public static function getImageInfo($url, $project)
	{
		$data = array('width' => 200, 'height' => 300, 'size' => 200000, 'mine' => 'image/jpeg',);
	    if ($project != '' && $url != '' && is_string($url))
	    {
	    	$source = self::getImageUrl($url, 'source', $project);
	    	if(strpos($source,'_') !== false)
	    	{
	    		$imageUrl = strstr($source, '_', true) . '?imageInfo';
	    	}
	    	else
	    	{
	    		$imageUrl = $source . '?imageInfo';
	    	}
	    	// 设置一个超时时间,单位为秒
	    	$context = stream_context_create(array(
	    			'http' => array('timeout' => 3,),
	    	));
	    	$temp = @file_get_contents($imageUrl, false, $context);
	    	if ($temp)
	    	{
	    	
	    		$temp = json_decode($temp, true);
	    		if (isset($temp['width']))
	    		{
	    			$data['width'] = $temp['width'];
	    			$data['height'] = $temp['height'];
	    			$data['mine'] = $temp['format'];
	    			$data['size'] = $temp['width'] * $data['height'];
	    		}
	    	}
	    }
	    return $data;
	}
	
	/**
	 * 分隔文件路径地址 (以文件后缀名"."符号分隔)
	 * 
	 * @param string $path (文件路径)
	 * @return array
	 */
	public static function partPath($path)
	{
	    $pos = strrpos($path, '.');
	    return array(
        	            'left' => substr($path, 0, $pos), 
        	            'right' => substr($path, $pos),
	                );
	}
	
	/**
	 * 创建文件夹
	 *
	 * @param string $path (文件路径)
	 * @return void
	 */
	public static function createFolder($path)
	{
		if (!file_exists($path))
		{
			$path = dirname($path);
			self::createFolder($path);
			@mkdir($path, 0755);
		}
	}
	
	/**
	 * 发送指令处理图片 (通过服务器调度, 进行图片处理. 此方法已不再使用)
	 *
	 * @param string $source 源文件地址
	 * @param string $size 需要的尺寸
	 * @param string $crop 切图方式
	 * @param string $target 目标文件地址
	 * @return void
	 */
	public static function makeImage($source, $size, $crop, $target) 
	{
		list($w, $h) = explode('x', $size);
		$size = array('w' => $w, 'h' => $h );
		$data = array(
    		'source' => $source, 
    		'target' => $target, 
    		'size' => $size, 
    		'mode' => $crop 
		);
		$c = Util_Gearman::client();
		$c->d(IMAGE_GMAGICK_FUNC, json_encode($data));
		$c->clones();
	}

	/**
	 * 获取文件存放的节点
	 *
	 * @return string ('01' | '02')
	 */
	public static function getRandNode()
	{
		$randNum = time() % 2;
		$randNum = ($randNum) ? $randNum : 2;
		return sprintf('%02d', $randNum);
	}
	
    /**
     * 获取图片系统键名
     * 
     * @param string $basename (文件名)
     * @return string ('img01' | 'img02')
     */
	public static function getSysKey($basename) 
	{
		return 'img' . substr($basename, 0, 2);
	}
	
	/**
	 * 生成上传密钥
	 * 
	 * @param string $porject (项目模块名称)
	 * @return string | false
	 */
	public static function genKey($porject)
	{
	    $projectData = $porject . 'Data';
	    if (property_exists('Config_File_Upload', $projectData) === true)
	    {
	        $uploadConfig = Config_File_Upload::${$projectData};
	        return Util_Utils_Function::base64_str_encode(
	                   Util_Utils_AuthCode::encode(
	                       json_encode($uploadConfig), Config_File_Upload::$key
	                   )
	               );
	    }
	    return false;
	}
	
	/**
	 * 获取上传的配置
	 * 
	 * @param string $project (项目模块名称)
	 * @return array
	 */
	public static function genConfig($project)
	{
	    if (property_exists('Config_File_Upload', $project) === true)
	    {
	        $config = (array) Config_File_Upload::${$project};
	        $config['randNode'] = Lib_Images::getRandNode();
	        $config['serverNode'] = 'img' . $config['randNode'];
	        $config['serverPath'] = Config_File_Image::$imageServer[$config['serverNode']] . $config['path'];
	        $config['thumbPath'] = Config_File_Image::$thumbPath[$config['serverNode']] . $config['path'];
	        $config['sourceUrl'] = Config_File_Image::$imageServerUrl[$config['serverNode']] . $config['path'];
	        $config['thumbUrl'] = Config_File_Image::$imageThumbUrl[$config['serverNode']] . $config['path'];
	        
	        return $config;
	    }
	    return array();
	}
	
}