Foros del Web » Programando para Internet » PHP »

GTphp - Convertir texto en imagen.

Estas en el tema de GTphp - Convertir texto en imagen. en el foro de PHP en Foros del Web. Hola, desde hace tiempo quería hacer esta herramienta en php para poder realizar los diseños web mas dinámicos sin estar tan limitado a las fuentes. ...
  #1 (permalink)  
Antiguo 10/08/2009, 09:32
 
Fecha de Ingreso: febrero-2008
Mensajes: 23
Antigüedad: 16 años, 1 mes
Puntos: 0
GTphp - Convertir texto en imagen.

Hola, desde hace tiempo quería hacer esta herramienta en php para poder realizar los diseños web mas dinámicos sin estar tan limitado a las fuentes.

Con esta aplicación tu le pasas un texto y el script te devuelve una imagen png con el texto. Ya se que habia por ahi algun otro script ke hacia algo parecido pero con este script puedes utilizar cualquier fuente ttf, elegir el color (incluso con capa alpha), el tamaño (tanto en puntos como pixeles), y la direcion del texto izq->der, arriba->abajo, abajo->arriba y el fondo de la imagen es siempre transparente para no molestar.

Bueno espero ke les guste y les sea de utilidad.

Si tienen alguna duda pues pregunten aqui mismo o a carlossc87 @ hotmail . com

(No sabia si ponerso en PHP o Diseño Web que el moderador decida, disculpas.)

Código PHP:
<?php
/*
 Nombre: Generador de imagenes de texto.
 Descripción: Se le pasa un texto y atributos sobre este y genera una imagen.
 Autor: Carlos Serramito Calvo
 - MODO DE USO -
 Al script se le pasan los atributos por GET -> gt.php?text=texto&color=0F051D00&...
  # Atributos:
    - text: El texto que se transformara en imagen.
    - font: El nombre de la fuente ( un archivo terminado en .ttf con el mismo nombre debe estar en la carpeta de las fuentes).
    - size: El tamaño de la fuente en puntos.
    - sizepx: El tamaño de la fuente en pixeles. (Si se pasa por size a este no se le hace caso)
    - direction: La direcion del texto. Los posibles valores son:
      + 0 : de izquierda a derecha.
      + 1 : de arriba a abajo.
      + 2 : de abajo a arriba.
    - color: El color del texto determinado por 4 numeros de 2 cifras hexadecimales (11223344), que corresponden a:
      + 11 : Cantidad de color rojo valores entre 00 y FF ( 0 y 255 )
      + 22 : Cantidad de color verde valores entre 00 y FF ( 0 y 255 )
      + 33 : Cantidad de color azul valores entre 00 y FF ( 0 y 255 )
      + 44 : Esto es el valor alpha valores entre 00 y 79 ( 0 y 127 ), por encima de 79 es como si fuera un 00.
  # Ejemplo completo
  
  <html>
  <head><title>Ejemplo</title></head>
  <body>
  <img src="gt.php?text=hola mundo&font=arial&size=15&direction=1&color=0000FF40" />
  </body>
  </html>
  
*/
/* VARIABLES GLOBALES */
define('FOLDER_FONTS','./fonts/');  //La carpeta de las fuentes
define('FOLDER_CACHE','./cache/');  //La cache donde se guardan las imagenes realizadas
define('CACHE',true);               //Activa el uso de la cache

function get_font(){
    if( isset(
$_GET['font']) ){
        
$font $_GET['font'];
        if( 
is_string($font) ){
            if( !
strstr($font,'../')  ){
                return 
$font;
            }
        }
    }
    return 
'arial';
}

function 
get_file_font($font){
    if( 
is_file(FOLDER_FONTS.$font.'.ttf') ){
        return 
FOLDER_FONTS.$font.'.ttf';
    }
}

function 
get_size(){
    if( isset(
$_GET['size']) ){
        
$size $_GET['size'];
        if( 
is_numeric($size) ){
            if( 
$size ){
                return 
$size/0.75;
            }
        }
    }
    if( isset(
$_GET['sizepx']) ){
        
$size $_GET['sizepx'];
        if( 
is_numeric($size) ){
            if( 
$size ){
                return 
$size;
            }
        }
    }
    return 
11;
}

function 
get_direction(){
    if( isset(
$_GET['direction']) ){
        
$direction $_GET['direction'];
        if( 
is_numeric($direction) ){
            if( 
$direction || $direction ){
                
$direction 0;
            }
            return 
$direction;
        }
    }
    return 
0;
}

function 
get_color(){
    if( isset(
$_GET['color']) ){
        
$color $_GET['color'];
        if( 
is_string($color) ){
            if( 
strlen($color) == ){
                return 
$color;
            }
        }
    }
    return 
'00000000';
}

function 
menor($v1,$v2,$v3,$v4){
    
$menor $v1;
    if(
$v2<$menor){ $menor $v2; }
    if(
$v3<$menor){ $menor $v3; }
    if(
$v4<$menor){ $menor $v4; }
    return 
$menor;
}

function 
mayor($v1,$v2,$v3,$v4){
    
$mayor $v1;
    if(
$v2>$mayor){ $mayor $v2; }
    if(
$v3>$mayor){ $mayor $v3; }
    if(
$v4>$mayor){ $mayor $v4; }
    return 
$mayor;
}

function 
make($text$size$direction$font$color){
    
$file_font get_file_font($font);

    
$width 0;
    
$height 0;
    
$offsetx 0;
    
$offsety 0;

    switch(
$direction){
        default: case 
0//de izquierda a derecha
            
$angle 0;
            
$box imageftbbox($size$angle$file_font$text);
            
$width $box[2] + (($box[2])*0.05);
            
$height $size;
            
$offsetx 0;
            
$offsety $height;
        break;
        case 
1//arriba a abajo
            
$angle = -90;
            
$box imageftbbox($size$angle$file_font$text);
            
$width $size;
            
$height $box[3];
            
$offsetx 0;
            
$offsety 0;
        break;
        case 
2//abajo a arriba
            
$angle 90;
            
$box imageftbbox($size$angle$file_font$text);
            
$width $size;
            
$height abs($box[3]) - ((abs($box[3]))*0.08);
            
$offsetx $width;
            
$offsety $height;
        break;
    }
    
    
$image imagecreatetruecolor$width$height);
    
    
imagesavealpha($imagetrue);
    
imagealphablending($imagefalse);

    
$text_color imagecolorallocatealpha($imagehexdec(substr($color,0,2)), hexdec(substr($color,2,2)), hexdec(substr($color,4,2)),hexdec(substr($color,6,2)));

    
$transparentColor imagecolorallocatealpha($image255255255127);
    
imagefill($image00$transparentColor);

    
$textColor imagecolorallocate($image200200200);
    
imagettftext($image$size$angle$offsetx$offsety$text_color$file_font$text);

    if(
CACHE){
        
imagepng($image,FOLDER_CACHE.name_cache($image,$text,$size,$direction,$font,$color));
    }

    
header('Content-Type: image/png');
    
imagepng($image);
    
    
imagedestroy($image);
}

function 
name_cache($im,$text,$size,$direction,$font,$color){
    return 
'c_'.$text.'_'.$size.'_'.$direction.'_'.$font.'_'.$color.'.png';
}

function 
gdVersion(){
    if (
function_exists('gd_info')) {
        
$ver_info gd_info();
        
preg_match('/\d/'$ver_info['GD Version'], $match);
        return 
$match[0];
    }
    return 
0;
}

function 
supportPNG(){
    
$info gd_info();
    return 
$info['PNG Support'];
}

function 
supportTTF(){
    
$info gd_info();
    return 
$info['FreeType Support'];
}

function 
is_file_casesensitive($name){
    
$dh opendir (FOLDER_CACHE);
    while ((
$file readdir($dh)) !== false) {
        if(
strcmp($file,$name)==0){
            return 
true;
        }
    }
    
closedir($dh);
    return 
false;
}

if( isset(
$_GET['text']) ){
    if( (!
extension_loaded('gd')) || (gdVersion() < 2) || (!supportPNG()) || (!supportTTF()) ){
        exit;
    }
    
    
$text $_GET['text'];
    
$size get_size();
    
$font get_font();
    
$direction get_direction();
    
$color get_color();
    
    if( 
CACHE ){
        
$name_cache name_cache($image,$text,$size,$angle,$font,$color);
        if( 
is_file_casesensitive($name_cache) ){
            
header('Content-Type: image/png');
            
readfile(FOLDER_CACHE.$name_cache);
        }else{
             
make($text,$size,$direction,$font,$color);
        }
    }else{
         
make($text,$size,$direction,$font,$color);
    }
}
?>
  #2 (permalink)  
Antiguo 10/08/2009, 09:37
Avatar de abimaelrc
Colaborador
 
Fecha de Ingreso: mayo-2009
Ubicación: En el planeta de Puerto Rico
Mensajes: 14.734
Antigüedad: 14 años, 10 meses
Puntos: 1517
Respuesta: GTphp - Convertir texto en imagen.

¿Porque no pasas ese codigo a POO?
__________________
Verifica antes de preguntar.
Los verdaderos amigos se hieren con la verdad, para no perderlos con la mentira. - Eugenio Maria de Hostos
  #3 (permalink)  
Antiguo 10/08/2009, 09:42
 
Fecha de Ingreso: febrero-2008
Mensajes: 23
Antigüedad: 16 años, 1 mes
Puntos: 0
Respuesta: GTphp - Convertir texto en imagen.

Sobre todo por vagancia jeje, igual mañana si tengo tiempo lo paso.
Gracias por la sugerencia.
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 00:13.