<?php
class cls_img
{
	// 生成路径
	protected static $path  = '';

	// 配置文件
	protected static $config = array();

	/**
	 * 初始化
	 *
	 * @param void
	 */
	public static function init()
	{
		$config = array();
		// 10列
		$config['colspan'] = 10;
		// 20行
		$config['rowspan'] = 34;
		// 宽度
		$config['width'] = 20 * $config['colspan'];
		// 高度
		$config['height'] = 20 * $config['rowspan'];
		// 文件路径
		$config['file_path'] = './default.png';
		// CSS样式
		$config['css_file_path'] = './default.css';
		// 宽度
		$config['_width'] = 20;
		// 高度
		$config['_height'] = 20;

		self::$config = $config;
	}

	/**
	 * 生成默认PNG图片
	 *
	 * @return void
	 */
	protected static function load_default_png()
	{
		if(!is_file(self::$config['file_path']))
		{
			$im  = imagecreatetruecolor(self::$config['width'], self::$config['height']);
			if($im)
			{
				// 白色
				$red = imagecolorallocate($im, 255, 255, 255);
				// 填充
				imagefill($im, 0, 0, $red);
				imagepng($im, self::$config['file_path']);
				imagedestroy($im);
			}
			else
			{
				return false;
			}
		}
		return imagecreatefrompng(self::$config['file_path']);
	}

	/**
	 * 生成图片
	 *
	 * @param string $file_name
	 * @param int $colspan
	 * @param int $rowspan
	 */
	public static function load_image($file_path, $colspan, $rowspan, $i)
	{
		if(is_file($file_path))
		{
			$im = self::load_default_png();
			if($im)
			{
				// 小图标位置
				$x = ($colspan - 1) * self::$config['_width'];
				$y = ($rowspan - 1) * self::$config['_height'];

				$css = ".ico-{$i}{background-position:-{$x}px -{$y}px;}\n";
				error_log($css, 3, self::$config['css_file_path']);

				// 判断类型
				$temp = getimagesize($file_path);
				$type = $temp[2];

				switch ($type)
				{
					case 1:
						$_im = imagecreatefromgif($file_path);
						break;
					case 2:
						$_im = imagecreatefromjpeg($file_path);
						break;
					case 3:
						$_im = imagecreatefrompng($file_path);
						break;
				}
				imagecopy($im, $_im, $x, $y, 0, 0,self::$config['_width'], self::$config['_height']);
				imagesavealpha($im, true);
				imagepng($im, self::$config['file_path']);
				imagedestroy($im);
				imagedestroy($_im);
			}
		}
		return true;
	}
}
set_time_limit(0);

cls_img::init();

$css = '';

// 行 与 列
$colspan = $rowspan = 1;
for ($i = 1; $i <= 340; $i++)
{
	if($i % 10 == 1)
	{
		$rowspan += 1;
	}
	$colspan = $i % 10;
	if($colspan == 0)
	{
		$colspan = 10;
	}
	echo '<pre>';

	cls_img::load_image("../img/{$i}.gif", $colspan, $rowspan - 1, $i);
}

echo 'ok';
?>