完善压缩处理类(支持主流的图像类型(jpg、png、gif)
2024-09-27 19:36:38
<?php
/*
* 图像压缩
*/
class Thumb
{
//成员属性
private $file; //原图文件
private $thumb_path; //压缩文本件保存的地址
//创建原图资源的函数(文件的mime类型和创建资源的映射关系)
private $create_func = array(
'image/png' => 'imagecreatefrompng',
'image/jpeg' => 'imagecreatefromjpeg',
'image/gif' => 'imagecreatefromgif'
);
//保存图像资源的函数
private $output_func = array(
'image/png' => 'imagepng',
'image/jpeg' => 'imagejpeg',
'image/gif' => 'imagegif'
);
//图像的mime类型
private $mime; public function __set($p,$v)
{
if(property_exists($this, $p)){
$this->$p = $v;
}
}
public function __get($p)
{
if(property_exists($this, $p)){
return $this->$p;
}
} //构造函数用来初始化属性
public function __construct($file)
{
if(!file_exists($file)){
echo '文件无效,请选择正确的文件';
exit;
}
//执行到中这里,说明文件有效
$this->file = $file;
$this->mime = getimagesize($file)['mime'];
} //参数1:压缩的范围宽度
//参数2:压缩的范围的高度
function makeThumb($area_w,$area_h)
{
//参数2:原图资源(将该图片资源压缩之后,再保存到目的地画布中)
$create_func = $this->create_func;
$src_image = $create_func[$this->mime]($this->file);
//参数3、4:目的地(画布的起点坐标)
$dst_x = 0;
$dst_y = 0;
//参数5、6:原图的(起点坐标)
$src_x = 0;
$src_y = 0;
//参数9、10:原图的宽度、高度
//通过imagesx()函数获得图像资源的宽度、imagesy()获得图像资源的高度
$src_w = imagesx($src_image);
$src_h = imagesy($src_image); //参数7、8:目的地(画布的宽度、高度)
//计算压缩的比例
if($src_w / $area_w >= $src_h / $area_h){
$scale = $src_w / $area_w;
}else{
$scale = $src_h / $area_h;
} $dst_w = (int)$src_w / $scale;
$dst_h = (int)$src_h / $scale; //参数1:目的地图像资源(通常指的是画布资源)
$dst_image = imagecreatetruecolor($dst_w, $dst_h);
$color = imagecolorallocate($dst_image, 255, 255, 255);
$color = imagecolortransparent($dst_image,$color); imagefill($dst_image, 0, 0, $color); imagecopyresampled($dst_image, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h); //可以保存、也可以输出到浏览器
//1. imagepng()增加第二个参数表示保存文件
//通常会把压缩之后的图片保存到thumb子目录中,按照日期格式的子目录保存
$sub_path = date('Ymd').'/';
$path = $this -> thumb_path;
if(!is_dir($path.$sub_path)){
mkdir($path.$sub_path,0777,true);
}
//thumb/20170402/
//压缩的图像的文件名,在原文件名的基础上增加前缀:thumb_bs.png
$origin_filename = basename($this->file);
$thumb_name = 'thumb_'.$origin_filename; //header("Content-Type:image/png");
$output_func = $this->output_func;
$output_func[$this->mime]($dst_image,$path.$sub_path.$thumb_name); //最后,一定要把文件地址返回(接收之后最后保存起来)
return $sub_path.$thumb_name;
}
} $thumb = new Thumb('bs.png');
$thumb -> thumb_path = 'thumb/';
$file = $thumb -> makeThumb(50, 50);
var_dump($file);
最新文章
- Hollister Outlet Store
- rewrite规则写法及nginx配置location总结
- Ftp软件
- 【AdaBoost算法】积分图代码实现
- 你足够了解Context吗?
- js自动判断浏览器类型跳转到手机版
- JS 实现取整
- codeforce 604B More Cowbell
- iOS之深入了解控制器View的加载
- VM Depot 喜迎中国本土开源镜像!
- Dom0级事件
- hdu N!
- Python3学习笔记02-基础语法
- collections模块
- ES6 Number
- delphi 中OutputDebugString 函数的妙用(转载)
- JUnit accuracy/failure/stress test区别
- jenkins 下载和安装
- CSS文本(Text)属性-----letter-spacing和text-align
- MVC源码分析 - Error过滤器