Convertir texto a imagen en PHP

En muchos casos, necesitamos crear imágenes dinámicas sobre la marcha o crear imágenes en base a un texto en nuestra aplicación web. Si cuentas con un requisito como este, no te preocupes, en este tutorial te proporcionamos un script de PHP que convierte texto a imagen y que lo guarda en formato PNG y JPG.

En este tutorial, vamos a mostrarte una forma sencilla de crear una imagen a partir de texto utilizando PHP. Para controlar el proceso de creación de texto a imagen, crearemos una clase PHP para ello. Utilizando esta clase de PHP puedes crear fácilmente una imagen y agregar múltiples líneas de texto sobre la misma imagen.

La librería GD la utilizaremos para crear y manipular el fichero de imagen en nuestro script PHP. Así que antes de empezar, asegúrate de que GD esté instalado en tu servidor.

Clase TextToImage

La clase de PHP TextToImage te ayuda a generar una imagen y a añadirle texto. La clase contiene cuatro funciones, que funcionan de esta manera:

  • createImage() - Crea una imagen a partir de texto. El string de texto que se pasa en la función, es lo que se va a escribir en la imagen. También se puede especificar el tamaño de fuente y el alto y ancho de la imagen.
  • showImage() - Devuelve la imagen que has creado mediante la función createImage()
  • saveAsPng() - Guarda la imagen en formato .png. Puedes especificar el nombre del fichero y donde quieres guardarla.
  • SaveAsJpg() - Guarda la imagen en formato .jpg. Puedes especificar el nombre del fichero y donde quieres guardarla.
<?php
/**
 * TextToImage class
 * This class converts text to image
 * 
 * @author    CodexWorld Dev Team
 * @link    http://www.codexworld.com
 * @license    http://www.codexworld.com/license/
 */
class TextToImage {
    private $img;
    
    /**
     * Create image from text
     * @param string text to convert into image
     * @param int font size of text
     * @param int width of the image
     * @param int height of the image
     */
    function createImage($text, $fontSize = 20, $imgWidth = 400, $imgHeight = 80){

        //text font path
        $font = 'fonts/the_unseen.ttf';
        
        //create the image
        $this->img = imagecreatetruecolor($imgWidth, $imgHeight);
        
        //create some colors
        $white = imagecolorallocate($this->img, 255, 255, 255);
        $grey = imagecolorallocate($this->img, 128, 128, 128);
        $black = imagecolorallocate($this->img, 0, 0, 0);
        imagefilledrectangle($this->img, 0, 0, $imgWidth - 1, $imgHeight - 1, $white);
        
        //break lines
        $splitText = explode ( "n" , $text );
        $lines = count($splitText);
        
        foreach($splitText as $txt){
            $textBox = imagettfbbox($fontSize,$angle,$font,$txt);
            $textWidth = abs(max($textBox[2], $textBox[4]));
            $textHeight = abs(max($textBox[5], $textBox[7]));
            $x = (imagesx($this->img) - $textWidth)/2;
            $y = ((imagesy($this->img) + $textHeight)/2)-($lines-2)*$textHeight;
            $lines = $lines-1;
        
            //add some shadow to the text
            imagettftext($this->img, $fontSize, $angle, $x, $y, $grey, $font, $txt);
            
            //add the text
            imagettftext($this->img, $fontSize, $angle, $x, $y, $black, $font, $txt);
        }
	return true;
    }
    
    /**
     * Display image
     */
    function showImage(){
        header('Content-Type: image/png');
        return imagepng($this->img);
    }
    
    /**
     * Save image as png format
     * @param string file name to save
     * @param string location to save image file
     */
    function saveAsPng($fileName = 'text-image', $location = ''){
        $fileName = $fileName.".png";
        $fileName = !empty($location)?$location.$fileName:$fileName;
        return imagepng($this->img, $fileName);
    }
    
    /**
     * Save image as jpg format
     * @param string file name to save
     * @param string location to save image file
     */
    function saveAsJpg($fileName = 'text-image', $location = ''){
        $fileName = $fileName.".jpg";
        $fileName = !empty($location)?$location.$fileName:$fileName;
        return imagejpeg($this->img, $fileName);
    }
}

Convertir texto a imagen en PHP

Incluye el fichero TextToImage.php (la clase que te hemos mostrado antes) y crea un objeto. Llama a la función createImage() y pásale la cadena de texto. Si quieres añadir múltiples líneas a la imagen, añade “n” antes de cada línea.

//include TextToImage class
require_once 'TextToImage.php';

//create img object
$img = new TextToImage;

//create image from text
$text = 'Bienvenido a programacion.net.nEl portal de programacion en castellano.';
$img->createImage($text);

Para mostrar la imagen, utiliza la función showImage().

//display image
$img->showImage();

Para guardar la imagen en formato PNG o JPG, utiliza las funciones saveAsPng() o saveAsJpg(). Especifica el nombre del fichero y su ubicación a la hora de guardar la imagen.

//save image as png format
$img->saveAsPng('programacionnet','images/');

//save image as jpg format
$img->saveAsJpg('programacionnet','images/');

Fuente: codexworld.com

COMPARTE ESTE ARTÍCULO

COMPARTIR EN FACEBOOK
COMPARTIR EN TWITTER
COMPARTIR EN LINKEDIN
COMPARTIR EN WHATSAPP