注意视频里写的两个info:
函数里的$info和$this->info是不同的变量
<?php
class Image{
private $image;
private $info;
public function __construct($src)
{
$info2 = getimagesize($src);
$this->info = array(
'width' => $info2[0],
'height' => $info2[1],
'type' => image_type_to_extension($info2['2'],false),
'mime' => $info2['mime']
);
$fun = "imagecreatefrom{$this->info['type']}";
$this->image = $fun($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;
}
public function show()
{
header("Content-type:".$this->info['mime']);
$funs = "image{$this->info['type']}";
$funs($this->image);
}
public function save($newimage)
{
$funs = "image{$this->info['type']}";
$funs($this->image,$newname.'.'.$this->info['type']);
}
public function __destruct()
{
imagedestroy($this->image);
}
}
?>
<title>给图片添加图片水印</title>
<?php
/*一、打开图片*/
$src = "001.png";
$info = getimagesize($src);
$type = image_type_to_extension($info[2],false);
$fun = "imagecreatefrom{$type}";
$image = $fun($src);
/*二、操作图片*/
$image_Mark = "logo.png";
$info2 = getimagesize($image_Mark);
$type2 = image_type_to_extension($info[2],false);
$fun2 = "imagecreatefrom{$type2}";
$water = $fun2($image_Mark);
//合并图片 0,0,$info[0],$info[1]将水印图片从原图的左上角顶点开始复制,0,0代表有多高复制多高,有多宽复制多宽。
imagecopymerge($image,$water,20,30,0,0,$info2[0],$info2[1],30);
imagedestroy($water);
/*三、输出图片*/
ob_clean();
header("content-type:".$info['mime']);
$funs = "image{$type}";
$funs($image);
$funs($image,"hi.".$type); //保存图片
/*四、销毁图片*/
imagedestroy($image);
?>
teat.php
<?php require "image_class.php"; $src = '1.jpg'; $image = new Image($src); $image->thumb(300,200); $image->show();
我的经过测试没有问题(代码如下):
<?php //封装成类-压缩图片 class Image{ private $image; private $info; //1.打开一张图片,读取到内存中 public function __construct($src){ $info = getimagesize($src);//获取图片信息放在$info里 $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); } //2.操作图片(压缩) 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; } //3.在浏览器中输出图片 public function show(){ header("Content-type:".$this->info['mime']); $funs = "image{$this->info['type']}"; $funs($this->image); } //4.把图片保存到硬盘里 public function save($newname){ $funs = "image{$this->info['type']}"; $funs($this->image,$newname.'.'.$this->info['type']); } //5.销毁图片 public function __destruct(){ imagedestroy($this->image); } }