龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > web编程 > php编程 >

长微博图片生成(可包含图片)

时间:2014-07-22 14:47来源: 作者: 点击:
分享到:
长微博图片生成(可包含图片,初步设置只允许前两张图片,另外本方法图片排版比较麻烦,故暂设置两张图片)简单的文本生成图片较为简单,但是如果需要富文本则相对比较麻烦,当然
长微博图片生成(可包含图片,初步设置只允许前两张图片,另外本方法图片排版比较麻烦,故暂设置两张图片)
简单的文本生成图片较为简单,但是如果需要富文本则相对比较麻烦,当然也有一些成型的源码,不过有些需要安装组件(一定的web环境),另外开源的painty似乎也不错,可以参考,这里只是自己实现p、img两个标签的图片生成,也花了一点时间(主要还是图片排版方面)
本功能本来是做wordpress的长微博推送,封装成函数供交流学习
<?php
/**
 * 
 * 长微博图片生成
 * @param unknown_type 文章id
 * @param unknown_type 文章内容(可根据id获取,这里直接传值)
 * @param unknown_type $img_path图片保存硬路径
 * @param unknown_type $img_path_url图片路径url
 */
function weibo_img_create($article_id,$text,$title='',$img_path='',$img_path_url=''){
	$font = dirname(__FILE__)."/droid.ttf";
	$pid = $article_id;
	//分段p标签处理
	$p_count = substr_count($text,'</p>'); //分段标签个数
	$content = preg_replace("/<\/p>/isU","\n",$text); //分段标签
	//图片img标签处理
	$all_img_height = 0;
	if(preg_match_all("/<img[^>]*src=\"([^\"]*)\"[^>]*>/", $content, $m)) {
		//只取前两张图片
		$m[0] = array_slice($m[0],0,2);
		$m[1] = array_slice($m[1],0,2);
		//保存图片资源
		foreach($m[1] as $i=>$src) {
			$imgs[] = $src;
		}
		//获取所有图片
		foreach($imgs as $i=>$image) {
			$ext = end(explode(".", $image));
			$im = null;
			switch($ext) {
			case "gif":
				$im = imagecreatefromgif($image);
				break;
			case "png":
				$im = imagecreatefrompng($image);
				break;
			case "jpeg":
				$im = imagecreatefromjpeg($image);
				break;
			case "jpg":
				$im = imagecreatefromjpeg($image);
				break;
			}
			$imgs[$i] = array(
					'0'=>$im,
					'height'=>floor(410/imagesx($im)*imagesy($im)),  //按比例缩放
				);
		}
		$content = strip_tags($content,'<img>');
		foreach($m[0] as $i=>$full) {
			//$replace_con = str_repeat("\n",ceil($imgs[$i]['height']/25));
			$content     = str_replace_once($full, 'img-pos-pos'.$i,$content); //只替换一次,防止出现相同的
			//$img_pos[$i] = mb_strpos($content, 'img-pos-pos'.$i); //使用去除img标签后的文本
			//$imgs[$i]['img_pos'] = $img_pos[$i];
			$imgs[$i]['full']    = $full;
			//$content = str_replace('img-pos-pos'.$i,$replace_con, $content);
			//$all_img_height += $imgs[$i]['height'];
		}
		$all_img_height += $imgs[0]['height'];
		$content = strip_tags($content.'endendend');//防止添加的换行符/空格被删除
	}
	$content = strip_tags($content);
	//$content = SpHtml2Text($content);//转化为文本
	$content = autowrap(12, 0, $font, $content, 395); // 自动换行处理
	if(!empty($imgs)){
		foreach($imgs as $i=>$v){
			$replace_con = str_repeat("\n",ceil($v['height']/25));
			$img_pos[$i] = mb_strpos($content, 'img-pos-pos'.$i); //使用去除img标签后的文本
			$imgs[$i]['img_pos'] = $img_pos[$i];
			$content = str_replace('img-pos-pos'.$i,$replace_con, $content);
		}
	}
	//$add_footer_input = "\n自定义底部添加\n\n\n";//自定义底部
	$input = str_replace("\r", "", stripcslashes($content));
	//$input = str_replace(" ", "", stripcslashes($input));
	//$title = explode("\n\n", $input);
	$ary = imagettfbbox (12, 0, $font, $input);
	$width = abs($ary[2] - $ary[0]) + 40;
	$height = abs($ary[1] - $ary[7]) + 220 + 215 + $p_count*25;
	
	//高清图片代替imagecreate(),若内容无图片建议使用imagecreate
	$img = @imagecreatetruecolor($width, $height);
	$bg_color=imagecolorallocate($img,229,231,230);
 	imagecolortransparent($img,$bg_color); // 设置为透明色,若注释掉该行则输出上面设置的背景
 	imagefill($img,0,0,$bg_color);
	$bgcolor = imagecolorallocate($img, '250', '250', '250');
	$bdcolor = imagecolorallocate($img, '250', '250', '250');
	$color = imagecolorallocate($img, '0', '0', '0');
	$color_title = imagecolorallocate($img, '250', '140', '0');
	$input = str_replace('endendend','',$input); //去除添加的干扰符
	imagettftext($img, 12, 0, 20, 160, $color, $font, $input);
	imagettftext($img, 18, 0, 21, 160, $color_title, $font, $title);
	imagerectangle($img, 0, 0, imagesx($img) - 1, imagesy($img) - 1, $bdcolor);
	
	//这里配置图标保存路径
	$img_path = dirname(__FILE__).'/../../weibo_img';
	$img_path_url = '/wp-content/weibo_img';
	
	//$img_path = empty($img_path)?'':$img_path;
	//$img_path_url = empty($img_path_url)?'':$img_path_url;
	
	//合成公共头部/底部图片
	if(file_exists($img_path.'/weibo_header.jpg') && file_exists($img_path.'/weibo_footer.jpg')){
		$child1 = imagecreatefromjpeg($img_path.'/weibo_header.jpg');
		$child2 = imagecreatefromjpeg($img_path.'/weibo_footer.jpg');  
   		imagecopymerge ( $img, $child1, 0, 40, 0, 0, imagesx ( $child1 ), imagesy ( $child1 ), 100 );
    	imagecopymerge ( $img, $child2, 0, $height-215, 0, 0, imagesx ( $child2 ), imagesy ( $child2 ), 100 );    
	}

	//图片加入(img标签)
	if(!empty($imgs)){
		$before_img_height = 0;
		foreach($imgs as $i=>$v){
			$child = $v[0];
			$part_content = mb_substr($content,0,$v['img_pos'],'utf-8');
			$rows_count = get_wrap_height(12, 0, $font, $part_content , 300);
			$dst_y = ($rows_count+7)*27 - 9 + $before_img_height;
			$before_img_height += $v['height'] + 25;//累计占用高度
			imagecopyresampled($img,$child,18,$dst_y,0,0,'410',$v['height'],imagesx($child),imagesy($child));
		}
	}
	
	//生成图片返回图片链接
	$file = empty($img_path)?'img/p-' . $pid . '.png':$img_path.'/p-'.$pid.'.png';
	imagepng($img, $file);
	imagedestroy($img);
	if(empty($img_path_url)){
  		return 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['REQUEST_URI']) . '/' . $file;
	}else{
		return 'http://' . $_SERVER['HTTP_HOST'] . $img_path_url . '/p-'.$pid.'.png';
	}
}

/** 
 * html转化为text 
 * @param inputString 
 * @return 
 */ 
function SpHtml2Text($str){
	//$str = strip_tags($str);
	$str = preg_replace("/<sty(.*)\\/style>|<scr(.*)\\/script>|<!--(.*)-->/isU","\n",$str);
	$alltext = "";
	$start = 1;
	for($i=0;$i<strlen($str);$i++){
		if($start==0 && $str[$i]==">"){
	   		$start = 1;
		}elseif($start==1){
			if($str[$i]=="<"){
			    $start = 0;
			    $alltext .= " ";
			}elseif(ord($str[$i])>31){
				$alltext .= $str[$i];
			}
		}
	}
	$alltext = str_replace(" "," ",$alltext);
	$alltext = preg_replace("/&([^;&]*)(;|&)/","",$alltext);
	$alltext = preg_replace("/[ ]+/s"," ",$alltext);
	return $alltext;
}

/**
 * 
 * 自动换行处理
 * @param unknown_type $fontsize字体大小
 * @param unknown_type $angle角度
 * @param unknown_type $fontface字体名称(最好使用绝对路径)
 * @param unknown_type $string字符串
 * @param unknown_type $width预设宽度
 */
function autowrap($fontsize, $angle, $fontface, $string, $width) {
	$content = "";
	$letter = array();
	// 将字符串拆分成一个个单字 保存到数组 letter 中
	for ($i=0;$i<mb_strlen($string);$i++) {
		$letter[] = mb_substr($string, $i, 1);
	}
	foreach ($letter as $l) {
		$teststr = $content." ".$l;
		$testbox = imagettfbbox($fontsize, $angle, $fontface, $teststr);
		// 判断拼接后的字符串是否超过预设的宽度
		if (($testbox[2] > $width) && ($content !== "")) {
			$content .= "\n";
		}
			$content .= $l;
	}
	return $content;
}

/**
 * 
 * 获取一定文字换行后的行数(高度)
 * @param unknown_type $fontsize字体大小
 * @param unknown_type $angle角度
 * @param unknown_type $fontface字体名称(最好使用绝对路径)
 * @param unknown_type $string字符串
 * @param unknown_type $width预设宽度
 */
function get_wrap_height($fontsize, $angle, $fontface, $string, $width) {
	$content = "";
	$rows_count = 0;
	$letter = array();
	// 将字符串拆分成一个个单字 保存到数组 letter 中
	for ($i=0;$i<mb_strlen($string);$i++) {
		$letter[] = mb_substr($string, $i, 1);
	}
	foreach ($letter as $l) {
		$teststr = $content." ".$l;
		$testbox = imagettfbbox($fontsize, $angle, $fontface, $teststr);
		// 判断拼接后的字符串是否超过预设的宽度
		if (($testbox[2] > $width) && ($content !== "")) {
			$content .= "\n";
			$rows_count += 1;
		}else{
			$rows_count += 1/$width;
		}
			$content .= $l;
	}
	return $rows_count;
}
/**
 * 
 * 替换函数(替换一次)
 * @param unknown_type $needle
 * @param unknown_type $replace
 * @param unknown_type $haystack
 */
function str_replace_once($needle, $replace, $haystack) {
	$pos = strpos($haystack, $needle);
	if ($pos === false) {
		return $haystack;
	}
	return substr_replace($haystack, $replace, $pos, strlen($needle));
}
?>

2. [文件] weibo_img_create.rar ~ 1MB     下载(57)     [全屏预览]

精彩图集

赞助商链接