使用php制作简单的缩略图

class image{
private $ext = array('jpg','png'); //支持的扩展名
public $imgSrc = ''; //原图片地址
public $thumbWidth = 200;//缩略为最大宽度为200的图片
public $thumbHeight = '';//缩略图的高度
public $width = '';//原图宽度
public $height = '';//原图高度
public $bili = '';//缩放比例
public $dstImgSrc = 'thumb/';//复制目标图片地址
public $currentExt = '';//当前图片扩展名

/**
* 判断文件是否符合上传类型,是否存在此文件,并且初始换文件信息
* @param string $path 图片的路径
*/
public function __construct($path){
if(is_file($path)){
$this->currentExt = substr($path,strpos($path,'.')+1);
if(!in_array($this->currentExt,$this->ext)){
die('不支持此扩展名!');
}
$this->imgSrc = $path;
$this->init();
} else {
die('不是一个文件!');
}
}

/**
* 初始换文件信息,获取文件宽高,生成的文件名,要缩放的比例
* return void
*/
public function init(){
$info = getimagesize($this->imgSrc);
$this->width = $info[0];
$this->height = $info[1];
$this->dstImgSrc .= $this->_getRoundName();
if($this->width <= $this->thumbWidth){
copy($this->imgSrc,$this->dstImgSrc);
return;
}
$this->bili = round($this->thumbWidth/$this->width,2);
$this->thumbHeight = $this->height * $this->bili;
}

/**
* 创建并生成图片
* return void
*/
public function createImg(){
$canvas = imagecreatetruecolor($this->thumbWidth,$this->thumbHeight);
$image = imagecreatefromjpeg($this->imgSrc);
imagecopyresampled($canvas, $image, 0, 0, 0, 0, $this->thumbWidth,$this->thumbHeight, $this->width, $this->height);
header('Content-Type: image/jpeg');
ImageJpeg ($canvas,$this->dstImgSrc);
imagedestroy($canvas);
}

/**
* 随机生成文件名,并判断是否存在此目录
* return string 文件名称
*/
private function _getRoundName(){
$dir = date('Ym');
$name = $dir.'/'.md5(time()).'.'.$this->currentExt;
if(!is_dir($this->dstImgSrc.$dir)){
mkdir($this->dstImgSrc.$dir,0777,true);
}
if(!is_file($this->dstImgSrc.$name)){
return $name;
} else {
$this->_getRoundName();
}
}
}
$image = new image('abc.jpg');
$isTrue = $image->createImg();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值