<?php
/**
* 图片上添加自己的文字水印
* @author Recoder
*/
class ImageAddText {
protected $imagePath;
protected $image;
protected $width;
protected $height;
protected $type; //文件类型
protected $mime;
protected $fontPath;
public function __construct() {
$this->imagePath = null;
$this->imagePath = null;
$image = null;
}
public function __destruct() {
if(isset($image)) {
imagedestroy($image);
}
}
//为图片和文字添加路径
public function addPath($filepath, $fontpath='') {
$this->imagePath = $filepath;
//获得图片信息
$info = getimagesize($filepath);
$this->width = $info[0];
$this->height = $info[1];
$this->type = image_type_to_extension($info[2], false);
$this->mime = $info['mime'];
//内存中创建图片
$func = "imagecreatefrom{$this->type}";
$this->image = $func($filepath);
$this->fontPath = $fontpath;
}
//添加文字
public function addText($text, $r=0, $g=0, $b=0, $x=20, $y=20, $fontsize=20, $alpha=20) {
//文字颜色
$color = imagecolorallocatealpha($this->image, $r, $g, $b, $alpha);
//文字写入图像中
imagettftext($this->image, $fontsize, 0, $x, $y, $color, $this->fontPath, $text);
}
//显示在浏览器上
public function display() {
header('Content-type:'.$this->mime);
$func = "image{$this->type}";
$func($this->image);
}
//保存
public function save($savepath='') {
$func = "image{$this->type}";
$func($this->image, $savepath);
}
}
使用
$a = new ImageAddText();
$a->addPath('day1/1.jpg', 'day1/font.ttf');
$a->addText('Hello World', 255, 255, 255, 100, 100, 50);
$a->display();