Desafío Carácter Marciano
#3 Solución de WiZ2
Ver código
|
Ver comentarios (0)
|
Descargar código
Fecha: 04 octubre 2006
Tamaño: 26404 caracteres
Comentarios: 0
Solución online:
Lo siento, pero no está disponible
Valoración









10.00
(1 votos)
"Al igual que Arias yo también hice una solución para comparar y evaluar la de los demás. La solución que he hecho es la mas rápida de todas las que he probado. Usa lineas para renderizar la imágen, usa la función "strspn" de PHP que acelera bastante la búsqueda, una buena paleta generada con funciones trigonométicas, tiene un buen aspect ratio y se puede personalizar algo (aunque no demasiado)."
Valora esta solución
<?php
//$start = array_sum(explode(' ', microtime())); register_shutdown_function('__end');
//function __end() { printf("Tiempo: %0.4f\n", array_sum(explode(' ', microtime())) - $GLOBALS['start']); }
/*
Programa de ejemplo para demostrar una solución óptima y personalizable.
Para el desafío "Carácter Marciano" de php-hispano | septiembre 2006
http://www.php-hispano.net/desafios/11/
Creado por Carlos Ballesteros Velasco (soywiz) miembro del jurado encargado
de evaluar las soluciones enviadas.
Requiere PHP >= 4
*/
// -- CONFIGURACIÓN ------
// Cambia el aspect ratio (afecta mucho al rendimiento)
$changearatio = true;
// Aspect ratio x / y
$aratio = 0.55;
// Muestra el tiempo empleado en la generación de la imagen
$showtime = true;
// Crea una paleta mediante funciones trigonométricas
$createpal = true;
$createpalbetween = array(31, 247);
// Muestra la imágen por la salida estándard en vez de guardarla en 'marcianos.png'
$showimage = true;
// -----------------------
// Utiliza la función array_sum introducida en PHP4.0.4, así que la
// definimos para aumentar la compatibilidad.
if (!function_exists('array_sum')) {
function array_sum($a) {
if (!is_array($a)) return false;
$r = 0; foreach ($a as $v) $r += $v; return $r;
}
}
// Utiliza la función array_combine introducida en PHP5, así que la
// definimos para aumentar la compatibilidad.
if (!function_exists('array_combine')) {
function array_combine($k, $v) {
if (!sizeof($k) || !sizeof($v)) return false;
reset($k); reset($v); $r = array();
do { $r[current($k)] = current($v); } while (next($k) && next($v));
return $r;
}
}
// Calcula el tiempo inicial
$start = array_sum(explode(' ', microtime()));
// Definición de mapa
$ccmap = array('M', 'N', 'H', '#', 'Q', 'U', 'A', 'D', '0', 'Y', '2', '$', '%', '+', '.', ' ');
if (isset($createpal) && $createpal) {
if (!isset($createpalbetween)) $createpalbetween = array(0, 255);
list($min, $max) = $createpalbetween; $dif = $max - $min;
// Crea una paleta de colores usando funciones trigronométricas
for ($n = 0, $ccmax = sizeof($ccmap); $n < $ccmax; $n++) {
$cvmap[$n] = ((sin(($n / ($ccmax - 1)) * M_PI - M_PI_2) + 1) / 2) * $dif + $min;
}
} else {
// Usa la paleta creada por ninbox
$cvmap = array(50, 65, 80, 95, 110, 125, 145, 160, 175, 195, 210, 220, 235, 240, 245, 250);
}
// Abre el ASCII art
$ls = file('marcianos.txt') or die('No se pudo abrir el fichero');
// Crea la imagen
$i = imageCreate($w = strlen(rtrim($ls[0])), $h = sizeof($ls)) or die('No se pudo crear la imagen');
// Reserva los colores para la imágen, utilizando los colores de la paleta
$cmap = array(); foreach (array_combine($ccmap, $cvmap) as $k => $v) $cmap[$k] = imageColorAllocate($i, $v, $v, $v);
// Renderiza la imagen mediante líneas y utilizando la función strspn para
// determinar las longitudes de línea.
for ($y = 0; $y < $h; $y++) {
$l = &$ls[$y]; $x = 0;
while ($x < $w) {
$cw = strspn($l, $cc = $l{$x}, $x);
imageLine($i, $x, $y, $x + $cw - 1, $y, $cmap[$cc]);
$x += $cw;
}
}
// Cambia el aspect ratio mediante un copyresampled
if (isset($changearatio) && $changearatio) {
// Elegimos las funciones apropiadas teniendo en cuenta que se podría usar PHP < 4.0.6 y GD1
$ficc = function_exists('imageCreateTrueColor') ? 'imageCreateTrueColor' : 'imageCreate';
$ficr = function_exists('imageCopyResampled') ? 'imageCopyResampled' : 'imageCopyResized';
$ir = $ficc($wr = $w, $hr = $h / $aratio);
$ficr($ir, $i, 0, 0, 0, 0, $wr, $hr, $w, $h);
$i = &$ir;
}
// Muestra el tiempo empleado en generar la imágen
if (isset($showtime) && $showtime) {
$text = sprintf(
'Generado en %1.4f segundos %s',
array_sum(explode(' ', microtime())) - $start,
(isset($changearatio) && $changearatio) ? '(con resampling)' : '(sin resampling)'
);
$white = imageColorAllocate($i, 0xFF, 0xFF, 0xFF);
if ($white == -1) $white = imageColorClosest($i, 0xff, 0xff, 0xff);
$black = imageColorAllocate($i, 0x00, 0x00, 0x00);
if ($black == -1) $black = imageColorClosest($i, 0xff, 0xff, 0xff);
imageString($i, 2, 9, 5, $text, $white);
imageString($i, 2, 8, 4, $text, $black);
}
// Vuelca la imágen por la salida estándar o al fichero 'marcianos.png'
if (isset($showimage) && $showimage) {
header('Content-Type: image/png');
imagePng($i);
} else {
imagePng($i, 'marcianos.png');
}
?>