先上一个工具类,提供了压缩,添加文字、图片水印等方法:
image.class.php
<?php
class Image {
private $info;
private $image;
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']}";
$this -> image = $fun($src);
}
public function thumb($width, $height) {
$imageThumb = imagecreatetruecolor($width, $height);
imagecopyresampled(
$imageThumb,
$this -> image,
0,
0,
0,
0,
$width,
$height,
$this -> info["width"],
$this -> info["height"]);
imagedestroy($this -> image);
$this -> image = $imageThumb;
}
public function waterMarkText($text, $fontPath, $fontSize, $color, $x, $y, $angle) {
$color = imagecolorallocatealpha(
$this -> image,
$color[0],
$color[1],
$color[2],
$color[3]);
imagettftext(
$this -> image,
$fontSize,
$angle,
$x,
$y,
$color,
$fontPath,
$text);
}
public function waterMarkImage($source, $x, $y, $alpha) {
$markInfo = getimagesize($source);
//3、获取水印图片类型
$markType = image_type_to_extension($markInfo[2], false);
//4、在内存创建图像
$markCreateImageFunc = "imagecreatefrom{$markType}";
//5、把水印图片复制到内存中
$water = $markCreateImageFunc($source);
//特别处理,设置透明
$color=imagecolorallocate($water,255,255,255);
imagefill($water,0,0,$color);
imagecolortransparent($water,$color);
//6、合并图片
imagecopymerge($this -> image, $water, $x, $y, 0, 0, $markInfo[0], $markInfo[1], $alpha);
}
public function show() {
header("Content-type:" . $this -> info['mime']);
$outputfunc = "image{$this -> info['type']}";
$outputfunc($this -> image);
}
public function save($newname) {
$outputfunc = "image{$this -> info['type']}";
$outputfunc($this -> image, $newname . '.' . $this -> info['type']);
}
public function __destruct() {
imagedestroy($this -> image);
}
}
?>
调用:
<?php
require "image.class.php";
$src = "aeroplane.jpg";
$image = new Image($src);
$source = "logo.png";
$image -> waterMarkImage($source, 0, 0, 30);
$image -> thumb(500, 500);
$fontPath = "STXINGKA.ttf";
$text = "文字图片水印";
$image -> waterMarkText(
$text,
$fontPath,
60,
array(255, 255, 255, 20),
10,
240,
0);
$image -> show();
$image -> save("image_mark");
?>
上面用到的图片和字体都跟代码文件在同一个目录下。
效果:
热门评论
好棒!