Home >Backend Development >PHP Tutorial >Chinese display in image function_PHP tutorial
Convert the GB code to UTF8. TTF in PHP supports the output of UTF8-encoded non-ASCII characters. After analyzing this code, we found that it is possible to achieve a mixed output of Chinese and ASCII images, which makes it more convenient when we operate image functions.
The code is as follows:
function gb2utf8($gb)
{
if(!trim($gb))
return $gb;
$ filename="gb2312.txt";
$tmp=file($filename);
$codetable=array();
while(list($key,$value)=each($tmp))
$codetable[hexdec(substr($value,0,6))]=substr($value,7,6);
$utf8="";
while($gb)
{
if (ord(substr($gb,0,1))>127)
{
$this=substr($gb,0,2);
$gb =substr($gb,2,strlen($gb)-2);
$utf8.=u2utf8(hexdec($codetable[hexdec(bin2hex($this))-0x8080]));
}
else
{
$this=substr($gb,0,1);
$gb=substr($gb,1,strlen($gb)-1);
$utf8 .=u2utf8($this);
}
}
/*$ret="";
for($i=0;$i
return $ret;*/
return $utf8;
}
function u2utf8($c)
{
/*for($i=0;$i
if ($c < 0x80) {
$str.=$c;
}
else if ($c < 0x800) {
$str.=chr(0xC0 | $ c>>6);
$str.=chr(0x80 | $c & 0x3F);
}
else if ($c < 0x10000) {
$str.=chr( 0xE0 | $c>>12);
$str.=chr(0x80 | $c>>6 & 0x3F);
$str.=chr(0x80 | $c & 0x3F);
}
else if ($c < 0x200000) {
$str.=chr(0xF0 | $c>>18);
$str.=chr(0x80 | $c>> 12 & 0x3F);
$str.=chr(0x80 | $c>>6 & 0x3F);
$str.=chr(0x80 | $c & 0x3F);
}
return $str;
}
?>
-------------------------- ------------------
Header ("Content-type: image/jpeg");
$im = imagecreate (800, 400 );
$black = ImageColorAllocate ($im, 0, 0, 0);
$white = ImageColorAllocate ($im, 255, 255, 255);
include("gb2utf8.php");
$str=gb2utf8("aaa中文了32434");
ImageTTFText ($im, 90, 10, 110, 300, $white, "/usr/share/fonts/default/TrueType/simsun.ttc ",
$str);
ImageJPEG ($im);
ImageDestroy ($im);
?>