php gd库 缩小图片_php 使用GD库压缩图片,添加文字图片水印

先上一个工具类,提供了压缩,添加文字、图片水印等方法:

image.class.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);

}

}

?>

调用:

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");

?>

上面用到的图片和字体都跟代码文件在同一个目录下。

效果:

979fd46cab5bdd8de4a72e0ecbff479f.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值