php GD库1 -> 自定义文字 转化为图片 Texttoimage类

本文介绍如何使用Texttoimage类来创建包含指定文本、字体、颜色和格式的图片。详细步骤包括类的构造函数参数说明、实例化操作及图片生成流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/** 
实例化操作 

$image = new Texttoimage(1000,200,50,"elephant.ttf","#FFA500",false,"#000000","png","1528065952qq.com");
$image->doimage();

**/

class Texttoimage{

  private $height; //生成的图片高度
  
  private $width;  //生成的图片宽度

  private $fontsize;//文字字体大小  默认为12号字体 

  private $font;  //文字字体
  
  private $bcolor;  //生成的图片背景颜色,默认为白色

  private $transparent;  // 默认不透明,png格式下有效

  private $textcolor;   //文字颜色,默认为黑色
  
  private $string;   //要格式化的字符串
  
  private $format;  //图片格式

  private $img;    //图片内存
  
   public function __construct($width,$height,$fontsize,$font,$bcolor,$transparent,$textcolor,$format,$string){
	 $this->width = $width;
	 $this->height = $height;
	 $this->fontsize = $fontsize;
	 $this->font = 'font' . DIRECTORY_SEPARATOR . $font;
	 $this->bcolor = $bcolor;
	 $this->transparent = $transparent;
	 $this->textcolor = $textcolor;
	 $this->format = strtolower($format);
	 $this->string = iconv("gb2312","utf-8",$string);
   }
  //具体实现函数
  public function doimage(){

	$this->img = imagecreatetruecolor($this->width,$this->height);  //生成真彩色
    $this->bcolor = imagecolorallocate($this->img, hexdec(substr($this->bcolor, 1, 2)), hexdec(substr($this->bcolor, 3, 2)), hexdec(substr($this->bcolor, 5, 2)));     //设置背景颜色值
    if($this->transparent){   
	  imagecolortransparent($this->img,$this->bcolor);  //设置背景透明
	}
    imagefill($this->img,0,0,$this->bcolor);    //填充背景颜色

    $this->textcolor = imagecolorallocate($this->img, hexdec(substr($this->textcolor, 1, 2)), hexdec(substr($this->textcolor, 3, 2)), hexdec(substr($this->textcolor, 5, 2)));     //设置文字颜色
    imagettftext($this->img,$this->fontsize,0,0,$this->height/1.4,$this->textcolor,$this->font,$this->string); //写入文字
    switch($this->format){
	  case "png":
          header("content-type:image/png");
	      imagepng($this->img);
		  break;
      case "jpg":
          header("content-type:image/jpeg");
	      imagejpeg($this->img);
		  break;
	  case "jpeg":
          header("content-type:image/jpeg");
	      imagejpeg($this->img);
		  break;
	  case "gif":
          header("content-type:image/gif");
	      imagegif($this->img);
		  break;
	  default:
          header("content-type:image/png");
	      imagepng($this->img);
	}
    imagedestory($this->img);
  }
 
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值