Commit fd2b07c5 authored by Bertrand Gauthier's avatar Bertrand Gauthier
Browse files

Util : ajout méthode qui Génère une image PNG d'un un texte sur fond gris...

Util : ajout méthode qui Génère une image PNG d'un un texte sur fond gris (extension gd requise). NB: problème d'encodage du 'ê' par exemple.
parent 2725e043
Loading
Loading
Loading
Loading
+47
Changes for src/UnicaenApp/Util.php: 47 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -5,6 +5,7 @@ namespace UnicaenApp;
use DateTime;
use UnicaenApp\Exception\LogicException;
use UnicaenApp\Exception\RuntimeException;
use Zend\Stdlib\Exception\ExtensionNotLoadedException;

/**
 * Regroupe des méthodes statiques utilitaires.
@@ -716,4 +717,50 @@ class Util

        return $rstr;
    }

    /**
     * Génère une image PNG correspondant à un texte sur fond gris.
     *
     * @param int    $width  Largeur de l'image à générer
     * @param int    $height Hauteur de l'image à générer
     * @param string $texte  Chaîne de caractères, avec des pipes à l'emplacement des retours à la ligne.
     *                       Exemple: "Utilisation | de la photo | non autorisée".
     * @return string
     * @throws ExtensionNotLoadedException L'extension PHP 'gd' doit être activée
     */
    static public function createImageWithText($texte, $width, $height)
    {
        if (! extension_loaded('gd')) {
            throw new ExtensionNotLoadedException("L'extension PHP 'gd' doit être activée pour fabriquer l'image");
        }

        $tmpImageFilePath = sys_get_temp_dir() . '/' . uniqid('unicaen-leocarte-') . '.png';

        // Create the image
        $img = imagecreatetruecolor($width, $height);

        // Create some colors
        $grey = imagecolorallocate($img, 245, 245, 245);
        $black = imagecolorallocate($img, 0, 0, 0);
        imagefilledrectangle($img, 0, 0, $width - 1, $height - 1, $grey);

        // Add the text
        $text = mb_convert_encoding($texte, 'ISO-8859-2', 'UTF-8');
        $x = 10;
        $y = 20;
        foreach (explode('|', $text) as $part) {
            imagestring($img, 2, $x, $y, $part, $black);
            $y += 15;
        }

        // Using imagepng() results in clearer text compared with imagejpeg()
        imagepng($img, $tmpImageFilePath);
        imagedestroy($img);

        $content = file_get_contents($tmpImageFilePath);

        unlink($tmpImageFilePath);

        return $content;
    }
}