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 conversion
- Var $ errormsg; // error message during conversion
Function gb2utf8 ($ instr = "")
- {
- $ This-> gb = $ instr;
- $ This-> setgb2312 ();
- ($ This-> gb = "")? 0: $ this-> convert ();
- }
Function setgb2312 ($ instr = "gb2312.txt ")
- {// Set the gb2312code file to 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 School bbs.it-home.org)
Function convert ()
- {// Convert the gb2312 string to the utf8 string. you must set $ gb in advance.
- $ This-> utf8 = "";
- If (! Trim ($ this-> gb) | $ this-> errormsg! = ""){
- Return ($ this-> utf8 = $ this-> errormsg );
- }
- $ Str = $ this-> gb;
While ($ str ){
- If (ord (substr ($ str, 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;
- }
- }
- ?>
Test example:
- // Php code conversion
- Header ("content-type: image/png ");
- $ Im = imagecreate (400,300 );
- $ Black = imagecolorallocate ($ im, 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 );
- ?>
Code description: you need to correctly set the font file. make sure that you can use font directly (without gb2utf8) to output English. |