工作中遇到使用GD库生成图片,在图片上写文本时,出现了乱码。 PHP GD 库 使用 imagettftext 向图像写入文本时 文本包含命名实体 (如:???) 如何转 UTF-8
function createImg()
{
$nickname = 'E李 ?';
ob_clean();
$xWidth = 0;
$nicknameWidth = 330;
$nicknameHeight = 56;
$image = imagecreatetruecolor(640, 1008);
$white = imagecolorallocate($image, 0, 255, 0);
$black = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $white);
$regularFontPath = resource_path('font/SourceHanSansSC-Regular.otf');
$nickname = removeEmojiChar($nickname);
$text = toEntities($nickname, "html-entities", "utf-8");
imagettftext($image, $nicknameSize, 0, $xWidth, $yTextHeight, $black, $nicknameFont, $text);
header("Content-Type: image/png");
imagepng($image);
imagedestroy($image);
}
function toEntities($string)
{
$len = strlen($string);
$buf = "";
for ($i = 0; $i < $len; $i++) {
if (ord($string[ $i ]) <= 127) {
$buf .= $string[ $i ];
} else if (ord($string[ $i ]) < 192) {
$buf .= "�";
} else if (ord($string[ $i ]) < 224) {
$buf .= sprintf("&#%d;", ((ord($string[ $i + 0 ]) & 31) << 6) + (ord($string[ $i + 1 ]) & 63));
$i += 1;
} else if (ord($string[ $i ]) < 240) {
$buf .= sprintf("&#%d;", ((ord($string[ $i + 0 ]) & 15) << 12) + ((ord($string[ $i + 1 ]) & 63) << 6) + (ord($string[ $i + 2 ]) & 63));
$i += 2;
} else {
$buf .= sprintf("&#%d;", ((ord($string[ $i + 0 ]) & 7) << 18) + ((ord($string[ $i + 1 ]) & 63) << 12) + ((ord($string[ $i + 2 ]) & 63) << 6) + (ord($string[ $i + 3 ]) & 63));
$i += 3;
}
}
return $buf;
}
function removeEmojiChar($str)
{
$mbLen = mb_strlen($str);
$strArr = [];
for ($i = 0; $i < $mbLen; $i++) {
$mbSubstr = mb_substr($str, $i, 1, 'utf-8');
if (strlen($mbSubstr) >= 4) {
continue;
}
$strArr[] = $mbSubstr;
}
return implode('', $strArr);
}
|