<?php
/**
* 生成缩略图
* @author Recoder
*/
class ImageThumb {
protected $type; //图片类型(后缀)
protected $image; //原图资源
protected $width;
protected $height;
protected $mime; //类型
protected $thumb; //缩略图资源
public function __construct() {
$this->image = null;
$this->thumb = null;
}
public function __destruct() {
if(isset($this->thumb)) {
imagedestroy($this->thumb);
}
}
//添加原图路径
public function addPath($src) {
$info = getimagesize($src);
$this->width = $info[0];
$this->height = $info[1];
$this->mime = $info['mime'];
$this->type = image_type_to_extension($info[2], false);
//根据类型创建动态函数名
$func = "imagecreatefrom{$this->type}";
$this->image = $func($src);
}
//创建一个缩略图
public function thumb($x=100, $y=100) {
//创建一个真彩图
$this->thumb = imagecreatetruecolor($x, $y);
//将图片压缩copy到真彩图上
imagecopyresampled($this->thumb, $this->image, 0, 0, 0, 0, $x, $y, $this->width, $this->height);
imagedestroy($this->image); //销毁内存中的原图
}
public function display() {
header('Content-type:', $this->mime);
$func = "image{$this->type}";
$func($this->thumb);
}
//将缩略图保存到指定路径中
public function save($savepath) {
header('Content-type:', $this->mime);
$func = "image{$this->type}";
if(!empty($savepath)) {
$func($this->thumb, $savepath);
}
}
}
例子:
$a = new ImageThumb();
$a->addPath('day1/2.jpg');
$a->thumb(200, 120);
$a->display();
$a->save('save.jpg'); //保存到同一目录下