Конвертация фото в ASCII Art на PHP

Генератор ascii рисунков или артов на PHP.

До:
Конвертация фото в ASCII Art на PHP

После:
Конвертация фото в ASCII Art на PHP


Создаем файл: ascii.class.php

Код:
<?php

class Ascii
{
	var $headers, $image, $url;
	var $size = 2; 
	var $quality = 2; 
	var $color = false; 
	var $chars = array('@', '#', '+', '\'', ';', ':', ',', '.', '`', ' ');
	var $color_char = '#'; 
	const max_filesize = 6000000; 
	
	public function __construct($url = 'http://abcvg.com/logo.png')
	{
		$this->url = $url;
		
		$opts = array(
			'http' => array(
				'method' => 'HEAD'
				)
			);
			
		$context = stream_context_get_default($opts);
		$this->headers = get_headers($this->url, 1);
		
		if(strstr($this->headers[0], '200') !== false) 
		{
			if($this->headers['Content-Length'] < self::max_filesize) 
			{
				if($this->is_image($this->headers['Content-Type']) !== false) 
				{
					switch($this->headers['Content-Type'])
					{
						case image_type_to_mime_type(IMAGETYPE_GIF):
							$this->image = imagecreatefromgif($this->url);
							break;
						case image_type_to_mime_type(IMAGETYPE_JPEG):
							$this->image = imagecreatefromjpeg($this->url);
							break;
						case image_type_to_mime_type(IMAGETYPE_PNG):
							$this->image = imagecreatefrompng($this->url);
							break;
						case image_type_to_mime_type(IMAGETYPE_WBMP):
							$this->image = imagecreatefromwbmp($this->url);
							break;
						case image_type_to_mime_type(IMAGETYPE_XBM):
							$this->image = imagecreatefromxbm($this->url);
							break;
						default:
							die('Something\'s gone horribly wrong...');
							break;
					}
					
					
				}
				else
				{
					$this->error('Could not determine image type (' . $this->headers['Content-Type'] . '), please use a format compatible with the GD library.');
				}
			}
			else
			{
				$this->error('Sorry, you image is too large. Please limit filesize to ' . round(self::max_filesize / 1024) . 'KB.');
			}
		}
		else
		{
			$this->error('URL ' . $this->url . ' cannot be accessed. Please check the file exists :-).');
		}
	}
	
	public function error($message)
	{
		echo '<div class="error">' . $message . '</div>';
	}
	
	public function is_image($content_type)
	{
		switch($content_type)
		{
			case image_type_to_mime_type(IMAGETYPE_GIF):
			case image_type_to_mime_type(IMAGETYPE_JPEG):
			case image_type_to_mime_type(IMAGETYPE_PNG):
			case image_type_to_mime_type(IMAGETYPE_WBMP):
			case image_type_to_mime_type(IMAGETYPE_XBM):
				return true;
				break;
			default:
				return false;
				break;
		}
	}
	
	public function draw($img = '')
	{
		if(empty($img) === true) $img = $this->image; 
		
		$width = imagesx($img);
		$height = imagesy($img); 
		
		if($this->color === true)
		{
			$pixel_color = imagecolorat($img, 1, 1);
			$rgb = imagecolorsforindex($img, $pixel_color);
			$output = '<span style="color: ' . $this->rgbtohex($rgb['red'], $rgb['green'], $rgb['blue']) . ';">';
		}
		else
		{
			$output = '';
		}
		
		for($y = 0; $y < $height; $y = $y + $this->quality)
		{
			for($x = 0; $x < $width; $x = $x + $this->quality)
			{
				$pixel_color = imagecolorat($img, $x, $y); 
				$rgb = imagecolorsforindex($img, $pixel_color); 
				
				if($this->color === true)
				{
					if($x > $this->quality && $y > $this->quality && $pixel_color == imagecolorat($img, $x - $this->quality, $y))
					{
						$char = $this->color_char;
					}
					else
					{
						$char = '</span><span style="color: ' . $this->rgbtohex($rgb['red'], $rgb['green'], $rgb['blue']) . ';">#';
					}
				}
				else
				{
					$brightness = $rgb['red'] + $rgb['green'] + $rgb['blue'];
					$brightness = round($brightness / (765 / (count($this->chars) - 1)));
					$char = $this->chars[$brightness];
				}
				$output .= $char;
			}
			$output .= "\n"; 
		}

		if($this->color === true)
		{
			$output .= '</span>';
		}
		
		return $output;
	}

	public function rgbtohex($red, $green, $blue)
	{
		$hex = '#';
		$hex .= str_pad(dechex($red), 2, '0', STR_PAD_LEFT);
		$hex .= str_pad(dechex($green), 2, '0', STR_PAD_LEFT);
		$hex .= str_pad(dechex($blue), 2, '0', STR_PAD_LEFT);
		return($hex);
	}

	public function __destruct()
	{
		imagedestroy($this->image);
	}
	
}

?>

Создаем файл index.php.

Код:
<?php

include_once('ascii.class.php');

if(isset($_GET['url']))
{
	$image = new Ascii($_GET['url']);
}
else
{
	$image = new Ascii();
}

if(isset($_GET['color'])) $image->color = ($_GET['color'] == 'on') ? true : false;
if(isset($_GET['size']))
{
	$image->size = $_GET['size'];
}
if(isset($_GET['quality']))
{
	$image->quality = $_GET['quality'];
}

if(isset($_GET['plaintext']) && $_GET['plaintext'] == 1)
{
	header('Content-Type: text/plain;');
	$image->color = false;
	echo $image->draw();
	exit();
}
elseif(isset($_GET['html']) && $_GET['html'] == 1)
{
	echo '<pre style="font: ' . $image->size * 2 . 'px/' . $image->size . 'px monospace;">';
	echo $image->draw();
	echo '</pre>';
	exit();
}
else
{
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
	<head>
		<meta http-equiv="author" content="Jonathan Ford" />
		<title>ASCII Art - <?php echo htmlentities($image->url) ?></title>	
	</head>
	<body>
		<h1 class="white">ASCII Art Generator</h1>
<?php

	echo '<pre class="white" style="font: ' . $image->size * 2 . 'px/' . $image->size . 'px monospace; text-align: center;">';
	echo $image->draw();
	echo '</pre>';
}
?>


	</body>
</html>


Зайти на файл index.php и давать запрос GET: index.php?url=ссылка на картинку

И все. Готово.



Просмотров: 3759
1.01.2014, 16:39 -

Категория: Статьи » Программирование » PHP