您的位置:首页 > 编程语言 > PHP开发

php GD库的简单封装,图片压缩、文字水印、图片水印等方法

2016-12-07 17:27 701 查看
<?php
/**
* GD库的封装
*/
class gdimg{
private $imginfo;
private $image;

/**
* 创建图片
* @param string $src 图片地址
*/
function __construct($src){
$imginfo=getimagesize($src);//返回一个数组,[0]图片width,[1]图片height,[2]图片类型...
$this->imginfo=array('width' =>$imginfo[0] ,
'height'=>$imginfo[1],
'type'=>image_type_to_extension($imginfo[2],false),
'mime'=>$imginfo['mime'] );
$imgcreate="imagecreatefrom{$this->imginfo['type']}";
$this->image=$imgcreate($src);
}

/**
* 压缩图片
* @param   $width  压缩后宽度
* @param   $height 压缩后高度
*/
public function thumb($width,$height){
$img_thumb=imagecreatetruecolor($width, $height);
imagecopyresampled($img_thumb, $this->image, 0, 0, 0, 0, $width, $height, $this->imginfo['width'], $this->imginfo['height']);
imagedestroy($this->image);
$this->image=$img_thumb;
}

/**
* 为图片添加文字水印
* @param  string  $content  文字内容
* @param  string  $font     字体文件地址
* @param  integer $fontsize 字体大小
* @param  integer $top      在图片上的x坐标
* @param  integer $left     y坐标
*/
public function fontmark($content,$font='img/BAUHS93.TTF',$fontsize=15,$top=20,$left=195){
$col_black=imagecolorallocatealpha($this->image, 0, 0, 0, 50);
imagettftext($this->image, $fontsize, 0, $top, $left, $col_black, $font, $content);
}

/**
* 为图片添加图片水印
* @param  string  $mark_src 水印图片地址
* @param  integer $x        在源图片上的X坐标
* @param  integer $y        y坐标
* @param  integer $ap       水印图片透明度
*/
public function imgmark($mark_src,$x=170,$y=170,$ap=30){
$imginfo2=getimagesize($mark_src);
$type2=image_type_to_extension($imginfo2[2],false);
$imgcreate="imagecreatefrom{$type2}";
$water=$imgcreate($mark_src);
imagecopymerge($this->image, $water, $x, $y, 0, 0, $imginfo2[0], $imginfo2[1], $ap);
imagedestroy($water);
}

/**
* 输出图片
*/
public function show(){
header('Content-type:'.$this->imginfo['mime']);
$outimg="image{$this->imginfo['type']}";
$outimg($this->image);
}

/**
* 保存图片
* @param   $newname 保存图片名称
*/
public function save($newname){
$saveimg="image{$this->imginfo['type']}";
$saveimg($this->image,$newname.'.'.$this->imginfo['type']);
}

/**
* 利用析构函数销毁内存中的图片
*/
public function __destruct(){
imagedestroy($this->image);
}
}

?>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: