-
-
class gb2utf8
- {
- var $gb; // 待转换的gb2312字符串
- var $utf8; // 转换后的utf8字符串
- var $codetable; // 转换过程中使用的gb2312代码文件数组
- var $errormsg; // 转换过程之中的错误讯息
function gb2utf8($instr="")
- {
- $this->gb=$instr;
- $this->setgb2312();
- ($this->gb=="")?0:$this->convert();
- }
function setgb2312($instr="gb2312.txt")
- { // 设置gb2312代码文件,默认为gb2312.txt
- $this->errormsg="";
- $tmp=@file($instr);
- if (!$tmp) {
- $this->errormsg="no gb2312";
- return false;
- }
- $this->codetable=array();
- while(list($key,$value)=each($tmp)) {
- $this->codetable[hexdec(substr($value,0,6))]=substr($value,7,6);
- }
- } //(脚本学堂 bbs.it-home.org)
function convert()
- { // 转换gb2312字符串到utf8字符串,需预先设置$gb
- $this->utf8="";
- if(!trim($this->gb) || $this->errormsg!="") {
- return ($this->utf8=$this->errormsg);
- }
- $str=$this->gb;
while($str) {
- if (ord(substr($str,0,1))>127)
- {
- $tmp=substr($str,0,2);
- $str=substr($str,2,strlen($str));
- $tmp=$this->u2utf8(hexdec($this->codetable[hexdec(bin2hex($tmp))-0x8080]));
- for($i=0;$i$this->utf8.=chr(substr($tmp,$i,3));
- }
- else
- {
- $tmp=substr($str,0,1);
- $str=substr($str,1,strlen($str));
- $this->utf8.=$tmp;
- }
- }
- return $this->utf8;
- }
function u2utf8($instr)
- {
- for($i=0;$i$str="";
- if ($instr $str.=ord($instr);
- }
- else if ($instr $str.=(0xc0 | $instr>>6);
- $str.=(0x80 | $instr & 0x3f);
- }
- else if ($instr $str.=(0xe0 | $instr>>12);
- $str.=(0x80 | $instr>>6 & 0x3f);
- $str.=(0x80 | $instr & 0x3f);
- }
- else if ($instr $str.=(0xf0 | $instr>>18);
- $str.=(0x80 | $instr>>12 & 0x3f);
- $str.=(0x80 | $instr>>6 & 0x3f);
- $str.=(0x80 | $instr & 0x3f);
- }
- return $str;
- }
- }
- ?>
复制代码
测试例子:
-
-
//php编码转换
- header("content-type: image/png");
- $im = imagecreate(400,300);
- $black = imagecolorallocate($im, 0,0,0);
- $white = imagecolorallocate($im, 184,44,6);
- include("gb2utf8.php");
- $obj=new gb2utf8();
- $obj->gb="123abc中国456def测试正确";
- $obj->convert();
- imagettftext($im, 20, 0, 5, 50, $white, "simkai.ttf", $obj->utf8);
- imagepng($im);
- imagedestroy($im);
- ?>
复制代码
代码说明:
需要正确设置font文件,请先确认可以使用font直接(不使用gb2utf8)输出英文。
|