Save in image the contents of a variable in php

0

Investigating in the network I found how to add text to an image with the following programs:

File name: writingOverImage.php

<?php 

require_once 'class.textPainter.php';

$x = $_GET["x"];
$y = $_GET["y"];

$R = $_GET["r"];
$G = $_GET["g"];
$B = $_GET["b"];

$size = $_GET["size"];

$text = $_GET["text"];


$img = new textPainter('./writingOverImage.jpg', $text, './Franklin.ttf', $size);

if(!empty($x) && !empty($y)){
    $img->setPosition($x, $y);
}

if(!empty($R) && !empty($G) && !empty($B)){
    $img->setTextColor($R,$G,$B);
}

$img->show();

?>

File name: writingOverImageFile.php

<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Floating window with tabs</title>

<style>

/*
This defines the workspace where i place the demo.
*/
#container {
    text-align: left;
    background: #FFF;
    width: 865px;
    margin: 20px auto;
    padding: 20px;
    border-left: 1px solid #CCC;
    border-right: 1px solid #CCC;
    -moz-box-shadow: 0px 0px 10px #BBB;
    -webkit-box-shadow: 0px 0px 10px #BBB;
    box-shadow: 0px 0px 10px #BBB;
}
</style>

</head>
<body>


<div id="container">

<?php 
    if($_POST["sending"]=="yes"){
        if(strlen($_POST["text"]<50)){
            echo '
                <img id="imgFinal" src="writingOverImage.php?x=center&y=950&size=30&r=43&g=43&b=42&text='.$_POST["text"].'" />               
            ';

        }else{
            echo "The text is too large for my demo!! ";
        }

    }else{
        echo '<img id="imgFinal" src="writingOverImage.php?size=50&text=Hello world!!" />';

    }
?>


<form name="formulario" action="" method="post" class="contactoFormulario">
        <div class="caja"><input type="text" name="text" />Text you want to write over the image</div>

        <button class="botonFormulario" type="submit" name="Submit" value="Enviar" />Generate image</button>
        <input type="hidden" name="sending" value="yes" />
    </form>
</div>

</body>
</html>

File name: class.textPainter.php

<?php
/**
 * http://alvarotrigo.com
 *  
 * This class allows to print text over a given image.
 * It needs from a TrueType font format (ttf).
 * 
 * The resulting image will be show in png format.
 * 
 * @author alvarotrigolopez 
 * @see http://www.php.net/manual/es/ref.image.php
 */
class textPainter{
    private $img;
    private $textColor;
    private $position = array();
    private $startPosition = array();

    private $imagePath;
    private $text;
    private $fontFile;
    private $fontSize;
    private $format;


    /**
     * Class Constructor 
     * 
     * @param string $imagePath background image path
     * @param string $text text to print
     * @param string $fontFile the .ttf font file (TrueType)
     * @param integer $fontSize font size
     * 
     * @access public
     */
    public function __construct($imagePath, $text, $fontFile, $fontSize){       
        $this->imagePath = $imagePath;
        $this->text = $text;
        $this->fontFile = $fontFile;
        $this->fontSize = $fontSize;

        $this->setFormat();
        $this->setQuality();
        $this->createImage();
        $this->setTextColor();
        $this->setPosition();
    }

    /**
     * Sets the text color using the RGB color scale.
     * 
     * @param integer $R red quantity
     * @param integer $G gren quantity
     * @param integer $B blue quantity
     * 
     * @access public
     */
    public function setTextColor($R=230, $G=240, $B=230){
        $this->textColor = imagecolorallocate ($this->img, $R, $G, $B);
    }

    /**
     * Shows the resulting image (background image + text)
     * On the same format as the original background image.
     * 
     * @access public
     */
    public function show(){
        //show thumb

        header("Content-type: image/".$this->format);   
        //creates the text over the background image
        imagettftext($this->img, $this->fontSize, 0, $this->startPosition["x"], $this->startPosition["y"], $this->textColor, $this->fontFile, $this->text);

        switch ($this->format){
            case "JPEG":


                imagejpeg($this->img, NULL, $this->jpegQuality);
                //imagejpeg($this->img,"",$this->jpegQuality);
                break;
            case "PNG":
                imagepng($this->img);
                break;
            case "GIF":
                imagegif($this->img);
                break;
            case "WBMP":
                imagewbmp($this->img);
                break;
            default:
                imagepng($this->img);
        }
    }

    /**
     * Sets the quality of the resulting JPEG image.
     * Default: 85
     * @param integer $value quality
     * @access public
     */
    public function setQuality($value=85){
        $this->jpegQuality = $value;
    }

    /**
     * Calculates the X and Y coordinates for the desired position 
     * of the text. 
     * @param string $x x position: left, center, right or custom 
     * @param string $y y position: top, center, bottom or custom
     * @access public
     */
    public function setPosition($x="center", $y="center"){
        $this->position["x"] = $x;
        $this->position["y"] = $y;

        $dimensions = $this->getTextDimensions();

        if($x=="left"){
            $this->startPosition["x"] = 0;
        }
        else if($x=="center"){          
            $this->startPosition["x"] = imagesx($this->img)/2 - $dimensions["width"]/2;
        }
        else if($x=="right"){
            $this->startPosition["x"] = imagesx($this->img) - $dimensions["width"];
        }
        //custom
        else{
            $this->startPosition["x"] = $x;
        }

        if($y=="top"){
            $this->startPosition["y"] = 0 + $dimensions["heigh"];
        }
        else if($y=="center"){
            $this->startPosition["y"]  = imagesy($this->img)/2 + $dimensions["heigh"]/2;
        }
        else if($y=="bottom"){
            $this->startPosition["y"]  = imagesy($this->img);
        }
        //custom
        else{
            $this->startPosition["y"] = $y;
        }

    }

    /**
     * Determines the format of the background image and 
     * sets it for the final image result.
     * Supported formats: jpeg, jpg, png, gif, wbmp
     * @access private
     */
    private function setFormat(){

    $this->format = preg_replace("/.*\.(.*)$/","\1",$this->imagePath);
        //$this->format = ereg_replace(".*\.(.*)$","\1",$this->imagePath);
        $this->format = strtoupper($this->format);

        if($this->format=="JPG" || $this->format=="JPEG"){
            $this->format="JPEG";
        }
        else if($this->format=="PNG"){
            $this->format="PNG";
        }
        else if ($this->format=="GIF"){
            $this->format="GIF";
        }
        else if ($this->format=="WBMP"){
            $this->format="WBMP";
        }else{
            echo "Not Supported File";
            exit();
        }
    }

    /**
     * Create a new image to work with from the given background 
     * image.
     * Supported formats: jpeg, jpg, png, gif, wbmp
     * @access private
     */
    private function createImage(){
        if($this->format=="JPEG"){
            $this->img = imagecreatefromjpeg($this->imagePath);
        }
        else if($this->format=="PNG"){
            $this->img = imagecreatefrompng($this->imagePath);
        }
        else if ($this->format=="GIF"){
            $this->img = imagecreatefromgif($this->imagePath);
        }
        else if ($this->format="WBMP"){
            $this->img = imagecreatefromwbmp($this->imagePath);
        }else{
            echo "Not Supported File";
            exit();
        }
    }

    /**
     * Sets the font file for the text.
     * 
     * @param string $fontFile the .ttf font file (TrueType)
     * @access public
     */
    public function setFontFile($fontFile){
        $this->fontFile = $fontFile;

        //recalculate the text position depending on the new font file
        $this->setPosition($this->position["x"], $this->position["y"]);
    }

    /**
     * Sets the font size for the text.
     * 
     * @param integer $fontSize 
     * @access public
     */
    public function setFontSize($fontSize){
        $this->fontSize = $fontSize;

        //recalculate the text position depending on the new font size
        $this->setPosition($this->position["x"], $this->position["y"]);
    }

    /**
     * It returns the dimensions of the text to print with the given 
     * size and font.
     * 
     * @return array containing the width and height (width,heigh) of the text to print.
     * @access public
     */
    private function getTextDimensions(){
        $dimensions = imagettfbbox($this->fontSize, 0, $this->fontFile, $this->text);

        $minX = min(array($dimensions[0],$dimensions[2],$dimensions[4],$dimensions[6]));
        $maxX = max(array($dimensions[0],$dimensions[2],$dimensions[4],$dimensions[6]));

        $minY = min(array($dimensions[1],$dimensions[3],$dimensions[5],$dimensions[7]));
        $maxY = max(array($dimensions[1],$dimensions[3],$dimensions[5],$dimensions[7]));

        return array(
            'width' => $maxX - $minX,
            'heigh' => $maxY - $minY
        );
    }  
}

?>

But I could not save the result automatically in a jpg or png file, or put more than one text on the same image, thank you in advance.

Everything is saved here:

$img = new textPainter('./writingOverImage.jpg', $text, './Franklin.ttf', $size);

But after that line I can not put anything else because if it does not work anymore.

P.D. The program works with the font format "Franklin.ttf" if it does not find it does not work, they can use another letter format by changing the name of the font format file in the program, in the same way if the file does not exist writingOverImage.jpg

    
asked by Stravos77 17.02.2017 в 18:27
source

2 answers

1

Here is a small example of the GD library for the use you need:

<?php
// Cargo la imagen donde escribir los textos
$image = imagecreatefrompng('prueba.png');

//Header
header('Content-type: image/png');

// Algunos colores
$gris = imagecolorallocate($image, 128, 128, 128);
$negro = imagecolorallocate($image, 0, 0, 0);

// Textos a imprimir
$texto1 = 'Primer texto.';
$texto2 = 'Otro texto.';

// Establecer la variable de entorno para GD
// El archivo de fuente debe estar en la misma ruta del codigo
putenv('GDFONTPATH=' . realpath('.'));

//Fuente a utilizar (sin extension)
$fuente = 'arial';

// Añadir el texto1
imagettftext($image, 10, 0, 10, 20, $gris, $fuente, $texto1);

// Añadir el texto2
imagettftext($image, 20, 0, 10, 50, $negro, $fuente, $texto2);

// Genero imagen y libero memoria
imagepng($image);
imagedestroy($imagen);
?>

You can add as many texts as you want with the imagettftext function, note that I have commented enough for you to understand, any questions you ask me.

    
answered by 21.02.2017 / 00:06
source
1

personally to do that kind of work with images in PHP I use the GD library directly (which is the one that uses the codes that you found) is very simple (easier than the programs :), this is the documentation link:

link

If it gets complicated and you need it, consult me and I'll give you a simple example. Greetings!

    
answered by 18.02.2017 в 04:10