PHP function imagettftext() and unicode
Here's the solution that finally worked for me:
$text = "你好";
// Convert UTF-8 string to HTML entities
$text = mb_convert_encoding($text, 'HTML-ENTITIES',"UTF-8");
// Convert HTML entities into ISO-8859-1
$text = html_entity_decode($text,ENT_NOQUOTES, "ISO-8859-1");
// Convert characters > 127 into their hexidecimal equivalents
$out = "";
for($i = 0; $i < strlen($text); $i++) {
$letter = $text[$i];
$num = ord($letter);
if($num>127) {
$out .= "$num;";
} else {
$out .= $letter;
}
}
Converting the string to HTML entities works except that the function imagettftext() doesn't accept named entities. For example,
日本語
is OK, but
ç
is not. Converting back to ISO-8859-1, converts the named entities back to characters, but there is a second problem. imagettftext() doesn't support characters with a value greater than >127. The final for-loop encodes these characters in hexadecimal. This solution is working for me with the text that I am using (includes Japanese, Chinese and accented latin characters for Portuguese), but I'm not 100% sure it will work in all cases.
All of these gymnastics are needed because imagettftext() doesn't really accept UTF-8 strings on my server.
Working with GD ( imagettftext() ) and UTF-8 characters
As I continued my research I came up with an answer for my problem, this piece of code did it!
private function properText($text){
$text = mb_convert_encoding($text, "HTML-ENTITIES", "UTF-8");
$text = preg_replace('~^(&([a-zA-Z0-9]);)~',htmlentities('${1}'),$text);
return($text);
}
Now all the characters (and all the new ones I've seen) that troubled me are displayed correctly!
Unicode-compatible alternative to imagettftext()
I ended up invoking ImageMagick from within PHP:
$command = 'printf "'.$text.'" | convert -size x'.(5*$size).' -gravity center -background "#00000000" -fill "#000000FF" -font '.$fontpath.' -pointsize '.$size.' label:@- -trim '.$imagepath;
exec($command);
How to properly write unicode words to image using PHP imgttftext() function
You'll need an additional library to perform Arabic glyph joining. Check out AR-PHP.
Related Topics
How to Paginate Lines in a Foreach Loop with PHP
Setting a Connect Timeout with Pdo
Inserting Line Breaks into PDF
PHP Curly Braces in Array Notation
Max_File_Size in PHP - What's the Point
Function Ereg_Replace() Is Deprecated - How to Clear This Bug
PHP - Merge Two Arrays (Same-Length) into One Associative
Do I Really Need to Do MySQL_Close()
Pdo Error: SQLstate[Hy000]: General Error: 2031
Differencebetween PHP Require and Include
Is There a JavaScript Way to Do File_Get_Contents()
Overwrite Line in File with PHP
PHP Datetime Round Up to Nearest 10 Minutes
Pdo: Invalid Parameter Number: Mixed Named and Positional Parameters
Call to Undefined Method Maatwebsite\Excel\Excel::Load()
Order by Before Group by Using Eloquent (Laravel)
Xml Parse Error - Extra Content at the End of the Document
PHP Try-Catch Blocks: Are They Able to Catch Invalid Arg Types