wordpress文章内容生成图片的方法

请自行下载字体AlibabaPuHuiTi-3-45-Light.otf放在主题根目录下。

在主题函数文件functions.php中添加

function ii_get_content2image($imgwidth,$fontsize,$type = '0'){
ini_set('memory_limit', '512M');
$tid = get_the_ID();
$text = get_post_field('post_content', $tid); // 获取文章内容

// 设置文字内容
$textContent = preg_replace("/(<br\s*\/?>)/i", "\n", strip_tags($text,'<p> <br> <img>'));
$textContent = preg_replace('/[\x{1F600}-\x{1F64F}\x{1F300}-\x{1F5FF}\x{1F680}-\x{1F6FF}\x{2600}-\x{26FF}\x{2700}-\x{27BF}\x{1F1E0}-\x{1F1FF}\x{1F900}-\x{1F9FF}\x{1FA00}-\x{1FA6F}\x{1FA70}-\x{1FAFF}\x{1FBC0}-\x{1FBCF}\x{1FBD0}-\x{1FBD0}\x{1FBE0}-\x{1FBE0}\x{1FBF0}-\x{1FBF0}\x{1FC00}-\x{1FC00}\x{1FC70}-\x{1FC70}\x{1FD00}-\x{1FD3E}\x{1FD40}-\x{1FD40}\x{1FD50}-\x{1FD8F}\x{1FD92}-\x{1FD95}\x{1FD97}-\x{1FD97}\x{1FD99}-\x{1FDBF}\x{1FDC0}-\x{1FDCF}\x{1FDD0}-\x{1FDDF}\x{1FDE0}-\x{1FDFD}\x{1FDFE}-\x{1FDFE}\x{1FE00}-\x{1FE0F}\x{1FE10}-\x{1FE1F}\x{1FE20}-\x{1FE2F}\x{1FE30}-\x{1FE4F}\x{1FE50}-\x{1FE50}\x{1FE70}-\x{1FEFF}\x{1FF00}-\x{1FF00}\x{1FF01}-\x{1FF02}\x{1FF03}-\x{1FF03}\x{1FF04}-\x{1FF04}\x{1FF05}-\x{1FF05}\x{1FF06}-\x{1FF06}\x{1FF07}-\x{1FF07}\x{1FF08}-\x{1FF0A}\x{1FF0B}-\x{1FF0B}\x{1FF0C}-\x{1FF0E}\x{1FF0F}-\x{1FF0F}\x{1FF10}-\x{1FF10}\x{1FF11}-\x{1FF11}\x{1FF12}-\x{1FF12}\x{1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\x{1FF55}\x{1FF56}-\x{1FF56}\x{1FF57}-\x{1FF57}\x{1FF58}-\x{1FF58}\x{1FF59}-\x{1FF59}\x{1FF5A}-\x{1FF5A}\x{1FF5B}-\x{1FF5B}\x{1FF5C}-\x{1FF5C}\x{1FF5D}-\x{1FF5D}\x{1FF5E}-\x{1FF5E}\x{1FF5F}-\x{1FF5F}\x{1FF60}-\x{1FF60}\x{1FF61}-\x{1FF61}]/u', '', $textContent);
$textContent = preg_replace('/<p(.*?)>(.*?)<\/p>/s', "$2\n", $textContent);
$textContent = preg_replace("/\s*[\r\n]+|\s*<br\s*\/?>\s*/i", "\n", $textContent);//多个换行替换成1个换行
$text = html_entity_decode($textContent);
// 设置字体文件路径
$font_file = get_template_directory() . '/AlibabaPuHuiTi-3-45-Light.otf'; // 确保这个路径是正确的
$max_width = $imgwidth; // 图片的最大宽度
$font_size = $fontsize; // 文字大小
$image_height = 10; // 初始化图片高度
$line_height = $font_size*2; // 行间距,这里简单加了一些额外空间
$outimg = ABSPATH . 'conimg/';
if (!(is_dir($outimg))) @mkdir($outimg, 0775);
if(!empty($tid)) $outimg .= md5($tid.'_'.$imgwidth.'_'.$fontsize.'_'.$type).'.webp';
else $outimg .= md5(strtotime(time()),1).'.webp';
if(file_exists($outimg)){
$outimg = site_url().'/conimg/'.basename($outimg);
$outimg = str_replace(ABSPATH,site_url(),$outimg);
return $outimg;
}

// 检查字体文件是否存在
if (!file_exists($font_file)) {
die('字体文件不存在');
}
// 创建一个真彩色图像(确保GD库已启用)
$image = imagecreatetruecolor($max_width, $image_height);
$white = imagecolorallocate($image, 255, 255, 255);
$black = imagecolorallocate($image, 0, 0, 0);
imagefill($image, 0, 0, $white);
$parts = preg_split('/(<img[^>]+>)/', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
$isText = true; // 标记当前处理的是文本还是图片
// 精确版的文本分割以适应宽度
$lines = [];
$images = []; // 存储图片的服务器路径和尺寸信息
$current_line_width = 0;
$lines[] = '';//添加空行
foreach ($parts as $part) {
if ($isText) {
// 对文本进行必要的处理,计算内容,行数,高度
foreach (explode("\n", wordwrap($part, $max_width, "\n", true)) as $article) {
preg_match_all("/./u", $article, $words);
foreach ($words[0] as $word) {
if(trim($word) == "") continue;
$word_box = imagettfbbox($font_size, 0, $font_file, $word);
$word_width = $word_box[2] - $word_box[0];
if(preg_match('/[\x{3002}\x{ff01}\x{2018}\x{2019}\x{201c}\x{201d}\x{fe50}\x{fe51}\x{fe52}\x{ff08}\x{ff09}\x{ff0c}\x{ff1a}\x{ff1b}\x{ff1f}\x{ff0e}\x{2026}\x{2014}\x{fe41}\x{fe42}\x{fe43}\x{fe44}\x{ff5e}\x{301d}\x{3001}]/u', $word)) $word_width = $word_width*2;
// 如果加上新单词后超过最大宽度,则开始新的一行
if ($current_line_width + $word_width > $max_width) {
$lines[] = implode('', $current_line);
$current_line = [$word];
$current_line_width = $word_width;
} else {
$current_line[] = $word;
$current_line_width += $word_width + ($font_size /4); // 简单添加字间距
}
}
// 添加最后一行
if (!empty($current_line)) {
$lines[] = implode('', $current_line);
}
$current_line = [];
$current_line_width = 0;
$lines[] = '';//添加空行,隔开段落
}
} else {
// 对图片标签进行处理
// 处理图片标签并记录图片信息
preg_match_all('/<img[^>]*src=["\'](.*?)["\']/i', $part, $matches);
foreach ($matches[1] as $imageSrc) {
// 假设$imageSrc已经是服务器相对或绝对路径
if ((strpos($imageSrc, 'http') !== 0 || strpos($imageSrc, 'https') !== 0) && strpos($imageSrc, '//') !== 0) {
$imageSrc = site_url() . '/' .$imageSrc;
}
$imageSrc = str_replace(site_url(),ABSPATH,$imageSrc);
$imageSrc = str_replace('//','/',$imageSrc);
if (!file_exists($imageSrc)) continue;
list($width, $height) = @getimagesize($imageSrc);
if($width >= $max_width){
$newWidth = $max_width * 0.85;
$newHeight = $height * ($newWidth/$width);
}else{
$newWidth = $width;
$newHeight = $height;
}
$images[] = array(
'src' => $imageSrc,
'x' => ($max_width - $newWidth) / 2,
'y' => count($lines) * $line_height,
'w' => $width,
'h' => $height,
'nw' => $newWidth,
'nh' => $newHeight
);
}
if(count($images) > 0){
$imagesH = ceil($newHeight/$line_height);
for($i=0;$i<=$imagesH;$i++){
$lines[] = '';//添加空行
}
}
}
$isText = !$isText; // 切换到处理下一种类型(文本或图片)
}

// 计算总高度并重新创建图像以适应所有文字
$image_height = count($lines) * $line_height;
if($image_height > 10000) {
$image_height = '10000';//图片超高,仅返回图片前1万像素高度
$lines_len = ceil($image_height/$line_height) - 1;
$lines[$lines_len-3] = '';
$lines[$lines_len-2] = '图片超高,仅返回图片前1万像素高度';
$lines[$lines_len-1] = '';
$lines[$lines_len] = '';
$lines = array_slice($lines, 0, $lines_len);
}
$new_image = imagecreatetruecolor($max_width, $image_height);
imagefill($new_image, 0, 0, $white);
imagesavealpha($new_image, true);
$transparent = imagecolorallocatealpha($new_image, 255, 255, 255, 127);
//$backgroundColor = imagecolorallocate($new_image, 255, 255, 255); // 纯白色背景作为示例
imagefill($new_image, 0, 0, $transparent);

// 随机线条参数
$lineCount = 100; // 线条数量
$minLineWidth = 80; // 线条最小宽度
$maxLineWidth = 200; // 线条最大宽度
$minLineColor = 230; // 线条颜色范围下限
$maxLineColor = 255; // 线条颜色范围上限
// 绘制随机线条
for ($i = 0; $i < $lineCount; $i++) {
// 随机选择线条的起点和终点
$startX = rand(-50, $max_width+50);
$startY = rand(-50, $image_height+50);
$endX = rand(-50, $max_width+50);
$endY = rand(-50, $image_height+50);

// 随机选择线条的颜色和宽度
$lineColor = imagecolorallocate($new_image, rand($minLineColor, $maxLineColor), rand($minLineColor, $maxLineColor), rand($minLineColor, $maxLineColor));
$lineWidth = rand($minLineWidth, $maxLineWidth);
// 设置线条宽度
imagesetthickness($new_image, $lineWidth);
// 绘制线条
imageline($new_image, $startX, $startY, $endX, $endY, $lineColor);
}

// 在新图像上绘制文字
foreach ($lines as $i => $line) {
imagettftext($new_image, $font_size, 0, 10, ($i + 1) * $line_height-5, $black, $font_file, $line);
}

// 绘制图片到画布上
if(count($images) > 0){
foreach ($images as $imageInfo) {
// 计算图片在画布上的位置,这里以简单方式为例,实际可能需要更复杂的布局逻辑
$imagePath = $imageInfo['src'];
$imageX = $imageInfo['x'];
$imageY = $imageInfo['y'];
$imageW = $imageInfo['w'];
$imageH = $imageInfo['h'];
$imageNW = $imageInfo['nw'];
$imageNH = $imageInfo['nh'];
// 加载并复制图片到新图像
$imageToDraw = @imagecreatefromstring(file_get_contents($imagePath));
imagecopyresampled($new_image, $imageToDraw, $imageX, $imageY, 0, 0, $imageNW, $imageNH, $imageW, $imageH);
imagedestroy($imageToDraw); // 清理内存
}
}
imagewebp($new_image,$outimg,'80');
imagedestroy($new_image);
$outimg = site_url().'/conimg/'.basename($outimg);
$outimg = str_replace(ABSPATH,site_url(),$outimg);
return $outimg;
}

 

在内容页中添加

<?php if ( is_single() ) { ?>
<img src="<?php echo ii_get_content2image('650','14'); ?>" />
<?php } ?>

<img src="<?php echo ii_get_content2image('650','14'); ?>" />