-
-
class gb2utf8 - {
- var $gb; // The gb2312 string to be converted
- var $utf8; // The converted utf8 string
- var $codetable; // Array of gb2312 code files used during the conversion process
- var $errormsg; // Error message during the conversion process
function gb2utf8($instr="")
- {
- $this- >gb=$instr;
- $this->setgb2312();
- ($this->gb=="")?0:$this->convert();
- }
-
function setgb2312($instr="gb2312.txt")
- { // Set gb2312 code file, the default is 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);
- }
- } //(script Xuetangbbs.it-home.org)
function convert()
- { // Convert gb2312 string to utf8 string, $gb needs to be set in advance
- $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 < 0x80) {
- $str.=ord($instr);
- }
- else if ($instr < 0x800 ) {
- $str.=(0xc0 | $instr>>6);
- $str.=(0x80 | $instr & 0x3f);
- }
- else if ($instr < 0x10000) {
- $str.= (0xe0 | $instr>>12);
- $str.=(0x80 | $instr>>6 & 0x3f);
- $str.=(0x80 | $instr & 0x3f);
- }
- else if ($ instr < 0x200000) {
- $str.=(0xf0 | $instr>>18);
- $str.=(0x80 | $instr>>12 & 0x3f);
- $str.=(0x80 | $instr> ;>6 & 0x3f);
- $str.=(0x80 | $instr & 0x3f);
- }
- return $str;
- }
- }
- ?>
-
Copy code
Test example:
-
- //php encoding conversion
- 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 China 456def test is correct";
- $obj->convert();
- imagettftext($im, 20, 0, 5, 50, $white, "simkai.ttf", $obj->utf8);
- imagepng( $im);
- imagedestroy($im);
- ?>
Copy code
Code description:
The font file needs to be set correctly. Please first confirm that you can use font to output English directly (without using gb2utf8).
|