前两篇博客总结了文字水印、图片水印、压缩图片的实现方法,现在将这三种应用封装成类,实现面向对象编程,思路同面向过程一样实现。
首先是封装成类文件供调用:
image.class.php文件
<?php
class image{
private $image;//保存中的图片
private $info;//图片的基本信息
/*
* 打开图片,读取到内存中
*/
public function __construct($src){
$info=getimagesize($src);
$this->info=array(
'width'=>$info[0],
'height'=>$info[1],
'type'=>image_type_to_extension($info[2],false),
'mime'=>$info['mime']
);
$func="imagecreatefrom{$this->info['type']}";
$this->image=$func($src);
}
/*
* 文字水印
*/
public function fontMark($content,$font_url,$size,$color,$local,$angle){
$col=imagecolorallocate($this->image, $color[0], $color[1],$color[2],$color[3]);//$color[3]透明度
imagettftext($this->image, $size,$angle,$local['x'],$local['y'],$col,$font_url,$content);
}
/*
* 图片水印
*/
public function imageMark($source,$local,$alpha){
$info2=getimagesize($source);
$type2=image_type_to_extension($info2[2],false);
$func2="imagecreatefrom{$type2}";
$water=$func2($source);
imagecopymerge($this->image, $water, $local['x'], $local['y'], 0, 0, $info2[0], $info2[1], 30);
imagedestroy($water);
}
/*
* 操作缩略
*/
public function thumb($width,$height){
$image_thumb=imagecreatetruecolor($width,$height);
imagecopyresampled($image_thumb, $image, 0, 0, 0, 0, $width, $height, $this->info['width'], $this->info['height']);
imagedestroy($this->image);
$this->image=$image_thumb;
}
/*
* 在浏览器中输出图片
*/
public function show(){
header("Content-Type:".$this->info['mime']);
$func="image{$this->info['type']}";
$func($this->image);
}
/*
* 把图片保存在硬盘中
*/
public function save($newname){
$func="image{$this->info['type']}";
$func($this->image,$newname.'.'.$this->info['type']);
}
/*
* 销毁图片
*/
public function _destruct(){
imagedestroy($this->image);
}
}
?>
调用封装的类文件中的对应方法实现相应的功能。
test.php文件
<?php
require 'image.class.php';
/*
* 测试缩略(压缩)
*/
// $src="aodi.jpg";
// $image=new image($src);
// $image->thumb(300, 200);
// $image->show();
/*
* 测试文字水印
*/
// $src="aodi.jpg";
// $image=new image($src);
// $content="holle word";
// $font_url="msyh.ttf";
// $size=20;
// $color=array(
// '0'=>255,
// '1'=>255,
// '2'=>255,
// '3'=>30
// );
// $local=array(
// 'x'=>20,
// 'y'=>20
// );
// $angle=10;//角度
// $image->fontMark($content,$font_url,$size,$color,$local,$angle);
// $image->show();
/*
* 测试图片水印
*/
$src="aodi.jpg";
$image=new image($src);
$source="imooc.png";
$local=array(
'x'=>20,
'y'=>20
);
$alpha=10;//透明度
$image->imageMark($source,$local,$alpha);
$image->show();
?>