3

When I call the below code with $text with Spanish I got correct text with image but When I call the same code with $text with Catalan I don't get correct text in the image. I understand that Spanish Special chars á and é are working but Catalan characters à and è are not working.

Can you please help me to correct this problem.

 <?php
    //$text = "Sándalo Ayurvédicos"; // Text in Spanish 
    $text = "Sàndal Ayurvèdics";  // Text in Catalan
    //$text = utf8_encode($text);
    //$text = utf8_decode($text);
    $img = "sample";
    $im = imagecreatetruecolor(25, 350);
    $black = imagecolorallocate($im, 0, 0, 0);
    imagecolortransparent($im, $black);
    $textcolor = imagecolorallocate($im, 73, 100, 23);
    imagestringup($im, 3, 10, 340, $text,$textcolor);
    imagepng($im, $img.'.png');
    imagedestroy($im);
    $imagename = $img.'.png';
    print '<img src="'.$imagename.'"></img>';
    ?>
App tester
  • 139
  • 1
  • 11

1 Answers1

2

The $string parameter is extremely ambiguous in PHP because strings in PHP don't carry the encoding with them and PHP doesn't unify the encoding of strings at all. In other words, they are byte arrays and not like Strings are usually in high level languages where all strings have internal unified unicode encoding and such parameter wouldn't be ambiguous.

I read from comments that the string must be in ISO-8859-2, which only supports á but not à.

You can use imagettftext that is documented to take the string in UTF-8 encoding, which is good because at least all characters can be drawn. But it requires a TrueType font, I am using Arial Unicode here:

<?php
header("Content-Type: image/png");


$text = "汉语/漢語"; //My PHP is already saved as UTF-8 in text editor - no conversion necessary

$im = imagecreatetruecolor(25, 350);
$black = imagecolorallocate($im, 0, 0, 0);
imagecolortransparent($im, $black);
$textcolor = imagecolorallocate($im, 73, 100, 23);

            //270 is the angle, from up-to-bottom
imageTtfText( $im, 12, 270, 10, 10, $textcolor, "./arial_unicode.ttf", $text );
        //12 is font size
//Camel-cased because imagettftext just looks horrible and php is case-insensitive

imagepng($im);
imagedestroy($im);

Here's the image that the above code generates:

http://i.imgur.com/pUxibBf.png

Esailija
  • 138,174
  • 23
  • 272
  • 326
  • +1 I've just learnt from you yet another stupid PHP design decision: a GD function that only accepts latin2... – Álvaro González Apr 18 '13 at 11:43
  • 1
    @ÁlvaroG.Vicario yeah that choice is completely arbitrary even if you don't know about Unicode. Maybe the author was Eastern European? Kinda like `T_PAAMAYIM_NEKDOTAYIM`... seriously :'( – Esailija Apr 18 '13 at 11:46