PHP 生成海报(头像,昵称,简介)

海报生成函数
/**
 * 生成宣传海报
 */
function createPoster($config = array(), $filename = "")
{
  //如果要看报什么错,可以先注释调这个header
  if (empty($filename)) header("content-type: image/png");
  $imageDefault = array(
    'left' => 0,
    'top' => 0,
    'right' => 0,
    'bottom' => 0,
    'width' => 100,
    'height' => 100,
    'opacity' => 100
  );
  $textDefault = array(
    'text' => '',
    'left' => 0,
    'top' => 0,
    'fontSize' => 32,       //字号
    'fontColor' => '255,255,255', //字体颜色
    'angle' => 0,
  );
  $background = $config['background']; //海报最底层得背景
  //背景方法
  $backgroundInfo = getimagesize($background);
  $backgroundFun = 'imagecreatefrom' . image_type_to_extension($backgroundInfo[2], false);
  $background = $backgroundFun($background);
  $backgroundWidth = imagesx($background);  //背景宽度
  $backgroundHeight = imagesy($background);  //背景高度
  $imageRes = imageCreatetruecolor($backgroundWidth, $backgroundHeight);
  $color = imagecolorallocate($imageRes, 0, 0, 0);
  imagefill($imageRes, 0, 0, $color);
  // imageColorTransparent($imageRes, $color);  //颜色透明
  imagecopyresampled($imageRes, $background, 0, 0, 0, 0, imagesx($background), imagesy($background), imagesx($background), imagesy($background));
  //处理了图片
  if (!empty($config['image'])) {
    foreach ($config['image'] as $key => $val) {
      $val = array_merge($imageDefault, $val);
      $info = getimagesize($val['url']);
      $function = 'imagecreatefrom' . image_type_to_extension($info[2], false);
      if ($val['stream']) {   //如果传的是字符串图像流
        $info = getimagesizefromstring($val['url']);
        $function = 'imagecreatefromstring';
      }
      $res = $function($val['url']);
      $resWidth = $info[0];
      $resHeight = $info[1];
      //建立画板 ,缩放图片至指定尺寸
      $canvas = imagecreatetruecolor($val['width'], $val['height']);

      $color = imagecolorallocatealpha($canvas, 255, 255, 255, 127);
      imagecolortransparent($canvas, $color);

      imagefill($canvas, 0, 0, $color);
      //关键函数,参数(目标资源,源,目标资源的开始坐标x,y, 源资源的开始坐标x,y,目标资源的宽高w,h,源资源的宽高w,h)
      imagecopyresampled($canvas, $res, 0, 0, 0, 0, $val['width'], $val['height'], $resWidth, $resHeight);
      $val['left'] = $val['left'] < 0 ? $backgroundWidth - abs($val['left']) - $val['width'] : $val['left'];
      $val['top'] = $val['top'] < 0 ? $backgroundHeight - abs($val['top']) - $val['height'] : $val['top'];
      //放置图像
      imagecopymerge($imageRes, $canvas, $val['left'], $val['top'], $val['right'], $val['bottom'], $val['width'], $val['height'], $val['opacity']); //左,上,右,下,宽度,高度,透明度
    }
  }
  //处理文字
  if (!empty($config['text'])) {
    foreach ($config['text'] as $key => $val) {
      $val = array_merge($textDefault, $val);
      list($R, $G, $B) = explode(',', $val['fontColor']);
      $fontColor = imagecolorallocate($imageRes, $R, $G, $B);
      $val['left'] = $val['left'] < 0 ? $backgroundWidth - abs($val['left']) : $val['left'];
      $val['top'] = $val['top'] < 0 ? $backgroundHeight - abs($val['top']) : $val['top'];
      imagettftext($imageRes, $val['fontSize'], $val['angle'], $val['left'], $val['top'], $fontColor, $val['fontPath'], $val['text']);
    }
  }
  //生成图片
  if (!empty($filename)) {
    // console
    $res = imagejpeg($imageRes, app()->getRootPath().$filename, 90); //保存到本地
    imagedestroy($imageRes);
    if (!$res) return false;
    return $filename;
  } else {
    imagejpeg($imageRes);     //在浏览器上显示
    imagedestroy($imageRes);
  }
}
应用配置函数
/**
 * @description: 生成海报
* @param {*} $result_user
* @param {*} $bg_result
* @param {*} $soname
* @param {*} $countpunch
* @return {*}
*/
public function get_poster($result_user = [],$bg_result = [],$soname='',$countpunch)
{
	// 海报信息
	if(empty($result_user)) return false;

	$rescode = new Qrcode();

	$config = array(
		'text' => array(
			array(
				'text' => $soname,
				'left' => 168,
				'top' => -472,
				'fontPath' => app()->getRootPath().'public/static/fonts/msyh.ttf', //字体文件
				'fontSize' => 28, //字号
				'fontColor' => '255,255,255', //字体颜色
				'angle' => 0,
			),
			array(
				'text' => $countpunch ?? 0,
				'left' => 200,
				'top' => -245,
				'bottom' => 0,
				'fontPath' => app()->getRootPath().'public/static/fonts/msyh.ttf', //字体文件
				'fontSize' => 50, //字号
				'fontColor' => '215,0,11', //字体颜色
				'angle' => 0,
			),
		),
		'image' => array(
			array(
				// 'url' => $result_user['user_pic'],
				'url' => $this->yuan_img($result_user['user_pic'],$result_user['id']),  // 用户头像
				'left' => 80,
				'top' => -458,
				'right' => 0,
				'stream' => 0,
				'bottom' => 0,
				'width' => 60,
				'height' => 60,
				'opacity' => 100
			),
			array(
				// 'url' => app()->getRootPath().'public/qrcode/100www.jpg',  // 二维码
				'url' => $rescode->getQrcode($result_user['id']),  // 二维码
				'left' => 390,
				'top' => -180,
				'right' => 0,
				'stream' => 0,
				'bottom' => 0,
				'width' => 250,
				'height' => 250,
				'opacity' => 100
			),
		),
		'background' => 'http://100.qhwww.com/public/' . $bg_result['clock_poster'],
		// 'background' => 'http://100.qhwww.com/public/storage/image/20210311/2554d613f7b5c0c0f92fe6745c518ad0.jpg',
	);
	$filename = 'public/qrcode/' . 'C-'.$result_user['id'] . '.jpg';
	createPoster($config, $filename);
	return $filename;
}

/**
 * @description: 图片裁剪为圆形图片
* @param {*} $imgpath
* @param {*} $id
* @return {*}
*/   
public function yuan_img($imgpath,$id)
{
	$ext   = pathinfo($imgpath);
	$tpic = app()->getRootPath()."/public/qrcode/" . 'T-' . $id . ".png";

	if(file_exists($tpic)){
		return $tpic;
	}
	$src_img = null;
	// switch ($ext['extension']) {
	// 	case 'jpg':
			$src_img = imagecreatefromjpeg($imgpath);
			// break;
	// 	case 'png':
	// 		$src_img = imagecreatefrompng($imgpath);
	// 		break;
	// }
	$wh  = getimagesize($imgpath);
	$w   = $wh[0];
	$h   = $wh[1];
	$w   = min($w, $h);
	$h   = $w;
	$img = imagecreatetruecolor($w, $h);
	//这一句一定要有
	imagesavealpha($img, true);
	//拾取一个完全透明的颜色,最后一个参数127为全透明

	$bg = imagecolorallocatealpha($img, 59, 255, 0, 127);
	imagecolortransparent($img, $bg);
	imagefill($img, 0, 0, $bg);

	$r   = $w / 2; //圆半径
	$y_x = $r; //圆心X坐标
	$y_y = $r; //圆心Y坐标
	for ($x = 0; $x < $w; $x++) {
		for ($y = 0; $y < $h; $y++) {
			$rgbColor = imagecolorat($src_img, $x, $y);
			if (((($x - $r) * ($x - $r) + ($y - $r) * ($y - $r)) < ($r * $r))) {
				imagesetpixel($img, $x, $y, $rgbColor);
			}
		}
	}

	$fileurl = app()->getRootPath()."/public/qrcode/" . 'T-' . $id . ".png";
	imagepng($img, $fileurl);
	imagedestroy($img);
	return $fileurl;
}

有时候需要换行来实现文章文章内容

  • 公共函数
/*
* 绘图文字分行函数
* by COoL
* - 输入:
* str: 原字符串
* fontFamily: 字体
* fontSize: 字号
* charset: 字符编码
* width: 限制每行宽度(px)
* - 输出:
* 分行后的字符串数组
*/
function autoLineSplit ($str, $fontFamily, $fontSize, $charset, $width) {
  $result = [];

  $len = (strlen($str) + mb_strlen($str, $charset)) / 2;

  // 计算总占宽
  $dimensions = imagettfbbox($fontSize, 0, $fontFamily, $str);
  $textWidth = abs($dimensions[4] - $dimensions[0]);

  // 计算每个字符的长度
  $singleW = $textWidth / $len;
  // 计算每行最多容纳多少个字符
  $maxCount = floor($width / $singleW);

  while ($len > $maxCount) {
    // 成功取得一行
    $result[] = mb_strimwidth($str, 0, $maxCount, '', $charset);
    // 移除上一行的字符
    $str = str_replace($result[count($result) - 1], '', $str);
    // 重新计算长度
    $len = (strlen($str) + mb_strlen($str, $charset)) / 2;
  }
  // 最后一行在循环结束时执行
  $result[] = $str;
  
  return $result;
}
  • 应用及配置函数
/**
 * @description: 换行的字符 (图片)  暂时没有到
* @param {*} $backImg 背景图
* @param {*} $uid 可以不要(我用在图名名称)
* @param {*} $contentText  内容(多行)
* @return {*}
*/
function LineFeed($backImg = null,$uid,$contentText){
	$randData = Db::name('question_bank')->orderRand()->limit(1)->select();
	
	if(isset($randData) || !empty($randData[0])){
		if (strlen($contentText) > 280) {
			$content = mb_substr($contentText,0,280,'utf-8').'...';
		}else{
			$content = $contentText;
		}
		$name = Db::name('phone_user')->update(['q_uid' => $randData['0']['id'],'id'=>$uid]);
	}else{
		$content = '要了解我们党和国家事业的来龙去脉汲取我们党和国家的历史经验,正确了解党和国家历史上的重大事件和重要人物。这对正确认识党情、国情十分必要,对开创未来也十分必要,因为历史是最好的教科书。';
	}
	$bg = imagecreatefromjpeg('http://100.qhwww.com/'.$backImg);
	$fontFamily = app()->getRootPath().'public/static/fonts/msyh.ttf';
	$fontSize = 20;
	$charset = 'utf8';
	$textcolor = imagecolorallocate($bg, 254, 237, 140);
	$lineHeight = 40;
	$startX = 80;
	$startY = 80;

	$lineWidth = imagesx($bg) - $startX - $startY;

	$lineArr = autoLineSplit($content, $fontFamily, $fontSize, $charset, $lineWidth);

	foreach ($lineArr as $k => $v) {
		// 这里加的750是往下多少px才开始   要是从顶部开始可以删了 (+ 750)
		imagettftext($bg, $fontSize, 0, $startX, ($startY + ($lineHeight * $k) + 750), $textcolor, $fontFamily, $v);
	}

	$filename = 'public/qrcode/' . 'C-'. $uid . '.jpg';;
	$localUrl = app()->getRootPath().$filename;
	imagejpeg($bg, $localUrl, 90);

	return $filename;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值