VendettaDroid
VendettaDroid

Reputation: 3111

Converting Text to Image using php script

I am dealing with non-English language and I want to display that text as image so that it will be supported even in the platforms that do not support this language. The problem is I am able to display text properly in text format but when it comes to image. It does not display image at all.

Link to Download the font: http://qfs.mobi/f394372 or just search for Surya.ttf in Google

Here is my code:

Code for text to image:

<?php
// Set the content-type
//mb_internal_encoding("UTF-8");
header('Content-Type: image/png');
require_once('seven.php');
// Create the image
$im = imagecreatetruecolor(400, 30);

// Create some colors
$white = imagecolorallocate($im, 255, 255, 255);
$grey = imagecolorallocate($im, 128, 128, 128);
$black = imagecolorallocate($im, 0, 0, 0);
imagefilledrectangle($im, 0, 0, 399, 29, $white);

// The text to draw
$text = getData();//'કેમ છો ?';
//echo $text;
// Replace path by your own font path
$font = 'Surya.ttf';

// Add some shadow to the text
imagettftext($im, 20, 0, 11, 21, $grey, $font, $text);

// Add the text
imagettftext($im, 20, 0, 10, 20, $black, $font, $text);

// Using imagepng() results in clearer text compared with imagejpeg()
imagepng($im);
imagedestroy($im);
?>

Code for getData():

<?php
function getData(){
$url = "http://www.sandesh.com/article.aspx?newsid=119068";
//$url = "http://www.sandesh.com/article.aspx?newsid=115627";
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
$output = curl_exec($curl);
curl_close($curl);
$DOM = new DOMDocument;
$output = mb_convert_encoding($output, 'HTML-ENTITIES', "UTF-8");
@$DOM->loadHTML($output);
$items = $DOM -> getElementById('lblNews');

echo "<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN'
'http://www.w3.org/TR/html4/loose.dtd'><html xmlns='http://www.w3.org/1999/xhtml'><head><meta http-equiv='Content-Type' content='text/html; charset=utf-8'></head><body><span>". $items -> nodeValue ."</span". "<br/></body></html>";
}
?>

Upvotes: 0

Views: 7987

Answers (2)

Amit Pandey
Amit Pandey

Reputation: 1

Some of the cases we need to create an image dynamically when the web page is loading, Then a question raised in the mind - Can I convert text to image in PHP? the answer is Yes! why not. For doing this activity you just need to do a few steps. These steps are given below:

Check your GD library extension is on in your current PHP version. If it does not enable simply just un-comment it. Include phpTextToImage class in your project. Create an object of this class. Call create image function with your text. Call save function with your file name and location.

function createImage($text, $textColor = '', $backgroundColor = '', $fontSize = 22, $imgWidth = 600, $imgHeight = 300) {

    //text font path
    $font = 'font/Pacifico-Regular.ttf';

    //create the image
    $this->image = imagecreatetruecolor($imgWidth, $imgHeight);

    $colorCode = array('#ffffff','#db3236', '#f4c20d', '#3cba54', '#4c53cc', '#56aad8', '#61c4a8');
    
    if ($backgroundColor == '') {
        /* select random color */
        $backgroundColor = $this->hexToRGB($colorCode[rand(0, count($colorCode) - 1)]);
    } else {
        /* select background color as provided */
        $backgroundColor = $this->hexToRGB($backgroundColor);
    }
    
    if ($textColor == '') {
        /* select random color */
        $textColor = $this->hexToRGB($colorCode[rand(0, count($colorCode) - 1)]);
    } else {
        /* select background color as provided */
        $textColor = $this->hexToRGB($colorCode[rand(0, count($textColor) - 1)]);
    }

    $textColor = imagecolorallocate($this->image, $textColor['r'], $textColor['g'], $textColor['b']);
    $backgroundColor = imagecolorallocate($this->image, $backgroundColor['r'], $backgroundColor['g'], $backgroundColor['b']);

    imagefilledrectangle($this->image, 0, 0, $imgWidth - 1, $imgHeight - 1, $backgroundColor);

    //break lines
    $splitText = explode("\\n", $text);
    $lines = count($splitText);
    $angle = 0;

    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->image) - $textWidth) / 2;
        $y = ((imagesy($this->image) + $textHeight) / 2) - ($lines - 2) * $textHeight;
        $lines = $lines - 1;
        //add the text
        imagettftext($this->image, $fontSize, $angle, $x, $y, $textColor, $font, $txt);
    }
    return true;
}

Now, create your project file where you want to create the image of your text dynamically, and just include class and create an object like this:

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

//create img object
$img = new phpTextToImage;

you can see full class here with example convert-text-to-image-in-php:

Upvotes: 0

LSerni
LSerni

Reputation: 57453

Your code is working (you forgot a closing span and the function does not return anything, but I imagine that's due to debugging).

What is happening is probably that the text you are loading contains whitespace or extra line feeds, and is then rendered outside your PNG.

Try with a larger PNG or try trimming the text with trim().

function getData()
{
    ...
    return trim($items->nodeValue);
}

Test code (working)

...or at least returning an image with something on it I can't read :-)

<?php

        function getData(){
                $url = "http://www.sandesh.com/article.aspx?newsid=119068";
                //$url = "http://www.sandesh.com/article.aspx?newsid=115627";
                $curl = curl_init($url);
                curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
                $output = curl_exec($curl);
                curl_close($curl);
                $DOM = new DOMDocument;
                $output = mb_convert_encoding($output, 'HTML-ENTITIES', "UTF-8");
                @$DOM->loadHTML($output);
                $items = $DOM -> getElementById('lblNews');

                return trim($items -> nodeValue);
        }

// Set the content-type
//mb_internal_encoding("UTF-8");
// require_once('seven.php');
// Create the image
$im = imagecreatetruecolor(400, 400);

// Create some colors
$white = imagecolorallocate($im, 255, 255, 255);
$grey = imagecolorallocate($im, 128, 128, 128);
$black = imagecolorallocate($im, 0, 0, 0);
imagefilledrectangle($im, 0, 0, ImageSX($im), ImageSY($im), $white);

// The text to draw
$text = getData();//'કેમ છો ?';
//echo $text;
// Replace path by your own font path
$font = 'Surya.ttf';

// Add some shadow to the text
imagettftext($im, 20, 0, 11, 21, $grey, $font, $text);

// Add the text
imagettftext($im, 20, 0, 10, 20, $black, $font, $text);

// Using imagepng() results in clearer text compared with imagejpeg()
header('Content-Type: image/png');
imagepng($im);
imagedestroy($im);

?>

Upvotes: 2

Related Questions