在GD中输出汉字的函数

感谢sadly为我们写出了在GD中输出汉字的函数,我在使用中发现此版本输出的字符串必须为纯中文,不能夹杂英文,随修改了此bug,与大家分享。

  1. <?
  2. //Program writen by sadly www.phpfensi.com
  3. //modified by agun 2013/6/20
  4. function gb2utf8($gb)
  5. {
  6. if(!trim($gb))
  7. return $gb;
  8. $filename="gb2312.txt";
  9. $tmp=file($filename);
  10. $codetable=array();
  11. while(list($key,$value)=each($tmp))
  12. $codetable[hexdec(substr($value,0,6))]=substr($value,7,6);
  13. $ret="";
  14. $utf8="";
  15. while($gb)
  16. {
  17. if (ord(substr($gb,0,1))>127)
  18. {
  19. $this=substr($gb,0,2);
  20. $gb=substr($gb,2,strlen($gb));
  21. $utf8=u2utf8(hexdec($codetable[hexdec(bin2hex($this))-0x8080]));
  22. for($i=0;$i<strlen($utf8);$i+=3)
  23. $ret.=chr(substr($utf8,$i,3));
  24. }
  25. else
  26. {
  27. $ret.=substr($gb,0,1);
  28. $gb=substr($gb,1,strlen($gb));
  29. }
  30. }
  31. return $ret;
  32. }
  33. function u2utf8($c)
  34. {
  35. for($i=0;$i<count($c);$i++)
  36. $str="";
  37. if ($c < 0x80) {
  38. $str.=$c;
  39. }
  40. else if ($c < 0x800) {
  41. $str.=(0xC0 | $c>>6);
  42. $str.=(0x80 | $c & 0x3F);
  43. }
  44. else if ($c < 0x10000) {
  45. $str.=(0xE0 | $c>>12);
  46. $str.=(0x80 | $c>>6 & 0x3F);
  47. $str.=(0x80 | $c & 0x3F);
  48. }
  49. else if ($c < 0x200000) {
  50. $str.=(0xF0 | $c>>18);
  51. $str.=(0x80 | $c>>12 & 0x3F);
  52. $str.=(0x80 | $c>>6 & 0x3F);
  53. $str.=(0x80 | $c & 0x3F);
  54. }
  55. return $str;
  56. }
  57. Header("Content-type: image/gif");
  58. $im = imagecreate(300,150);
  59. $bkg = ImageColorAllocate($im, 0,0,0);
  60. $clr = ImageColorAllocate($im, 255,255,255);
  61. $fnt = "c:windowsfontssimsun.ttf";
  62. //include("gb2utf8.php");
  63. $str = gb2utf8("中国agun阿棍");
  64. ImageTTFText($im, 30, 0, 50,50, $clr, $fnt, $str);
  65. ImageGif($im);
  66. ImageDestroy($im);
  67. ?>