<?php
require('image_class.php');
$src = 'tmp.jpg';
$font_url = 'msyh.ttc';
$logo_url = 'logo.png';
$content = 'Hello world';
$local = array(
'x'=> 20,
'y'=> 30
);
$color = array(
0 => 255,
1 => 255,
2 => 255,
3 => 20
);
$fontsize = 20;
$angle = -30;
$alpha = 30;
$image = new Image($src);
$image->fontmark($font_url,$content,$local,$color,$angle,$fontsize);
$image->imagemark($logo_url,$local,$alpha);
$image->thumb(150,100);
$image->show();
$image->move('imagemark');
?>
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'],
);
//在内存中创建一个同类型的图像
$fun = "imagecreatefrom{$this->info['type']}"; //imagecreatefromjpeg
//把图片复制到我们的内存
$this->image = $fun($src); //imagecreatefromjpeg($src);
}
//压缩图片方法
public function thumb($width, $height){
$image_thumb = imagecreatetruecolor($width, $height);
//核心步骤,将原图复制到真彩色图像,按照一定比例压缩
imagecopyresampled($image_thumb, $this->image, 0, 0, 0, 0, $width, $height, $this->info['width'], $this->info['height']);
imagedestroy($this->image);
$this->image = $image_thumb;
//销毁图片
// imagedestroy($image_thumb); //地址一致,不能销毁
}
//文字水印方法
public function fontmark($font_url,$content,$local,$color,$angle,$fontsize){
//设置字体颜色和透明度 参数1 内存中的图片 RGB参数
$col = imagecolorallocatealpha($this->image, $color[0], $color[1], $color[2], $color[3]);
//写入文字
imagettftext($this->image, $fontsize, $angle, $local['x'], $local['y'], $col, $font_url, $content);
}
//图片水印方法
public function imagemark($logo_url,$local,$alpha){
//获取图片信息
$info2 = getimagesize($logo_url);
//通过图片的编号取得图片的类型
$type_logo = image_type_to_extension($info2[2], false);
//在内存中创建一个同类型的图像
$funs = "imagecreatefrom{$type_logo}"; //imagecreatefromjpeg
//把水印复制到我们的内存
$water = $funs($logo_url); //imagecreatefromjpeg($src);
//合并图像
//imagecopymerge($image, $water, 20, 30, 0, 0, $info2[0], $info2[1], 25);
$this-> imagecopymerge_alpha($this->image, $water, $local['x'], $local['y'], 0, 0, $info2[0], $info2[1],$alpha);
//销毁水印
imagedestroy($water);
}
//解决imagecopy、imagecopymerge的合并方案(兼容方法)
public function imagecopymerge_alpha($dst_im, $src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h, $pct){
$cut = imagecreatetruecolor($src_w, $src_h);
imagecopy($cut, $dst_im, 0, 0, $dst_x, $dst_y, $src_w, $src_h);
imagecopy($cut, $src_im,0, 0, $src_x, $src_y, $src_w, $src_h);
imagecopymerge($dst_im, $cut, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h, $pct);
}
/*输出图片到浏览器*/
public function show(){
header("content-type:".$this->info['mime']);
$func = "image{$this->info['type']}";
$func($this->image);
}
/*输出图片到磁盘*/
public function move($newname){
header("content-type:".$this->info['mime']);
$func = "image{$this->info['type']}";
$func($this->image,$newname.'.'.$this->info['type']);
}
/*销毁图片*/
public function __destruct(){
imagedestroy($this->image);
}
}
?>