public function generate_captcha_image($code) {
$width = 120;
$height = 40;
$image = imagecreatetruecolor($width, $height);
// 颜色设置
$bg_color = imagecolorallocate($image, 245, 245, 245);
$text_color = imagecolorallocate($image, 30, 30, 30);
$line_color = imagecolorallocate($image, 180, 180, 180);
$noise_color = imagecolorallocate($image, 150, 150, 150);
// 填充背景
imagefill($image, 0, 0, $bg_color);
// 添加干扰线
for ($i = 0; $i < 5; $i++) {
imageline($image, rand(0, $width), rand(0, $height), rand(0, $width), rand(0, $height), $line_color);
}
// 添加噪点
for ($i = 0; $i < 200; $i++) {
imagesetpixel($image, rand(0, $width), rand(0, $height), $noise_color);
}
// 添加文字 - 改进字体处理
$font_size = 18;
$x = 10;
$font_path = plugin_dir_path(__FILE__) . 'arial.ttf';
// 检查字体文件是否存在
if (file_exists($font_path)) {
// 使用TrueType字体
for ($i = 0; $i < strlen($code); $i++) {
$y = rand(25, 30);
$angle = rand(-10, 10);
imagettftext($image, $font_size, $angle, $x, $y, $text_color, $font_path, $code[$i]);
$x += 22;
}
} else {
// 回退到基本字体
$font_size = 5; // GD库内置字体大小
$x = 10;
$y = rand(15, 25);
imagestring($image, $font_size, $x, $y, $code, $text_color);
}
// 输出图片
ob_start();
imagepng($image);
$image_data = ob_get_contents();
ob_end_clean();
imagedestroy($image);
return 'data:image/png;base64,' . base64_encode($image_data);
}
建站技巧 – WordPress AI自动写文章插件-极光AI Post
跳过内容