支持自定义图片宽高(像素)
支持图片另存,替换
话不多说直接上代码
// An highlighted block
<?php
//图片压缩类 仿微信
class compress
{
private $width = 0; //图片宽
private $height = 0; //图片高
private $defaults = 1280; //默认值;
private $suffix = ''; //图片后缀
private $name_url = ''; //压缩后的地址
private $in_arrays = array('jpg','jpge','png','gif'); //支持类型
//构造方法
public function __construct($default = 1280){
$this->defaults = $default;
}
public function __call($funname,$arr){
exit("你调用的函数:".$funname."() 不存在!");
}
//生成图片
public function implement($url='',$name_url='',$width = 0,$height = 0){
$this->url = $url;
$this->width = $width;
$this->height = $height;
$this->name_url = $name_url;
if(empty($this->url)){
exit("请传入图片 - -");
}
if(!in_array($this->Type_Img($this->url),$this->in_arrays)){
exit('原文件格式不正确 - -');
}
if(!file_exists($this->url)){
exit("文件不存在 - -");
}
if($this->width != 0 && $this->height !=0){
return $this->generate($this->width,$this->height);
}else{
return $this->proportion();
}
}
//获得文件类型;
public function Type_Img($url){
$url_s = explode('.',$url);
return array_pop($url_s);
}
//计算图片比例 默认值
private function proportion(){
list($w,$h) = getimagesize($this->url);
//条件一 宽高均 <= 1280,图片尺寸大小保持不变
if($w <= $this->defaults && $h <= $this->defaults){
$w = $w;
$h = $h;
}
if($w > $this->defaults || $h > $this->defaults){
if($w > $h){
$ratio = $w / $h;
}else{
$ratio = $h / $w;
}
$shearW = $w * $this->defaults / $h; //计算过的宽
$shearH = $h * $this->defaults / $w; //计算过的高
//条件二 宽或高 > 1280 && 宽高比 <= 2,取较大值等于1280,较小值等比例压缩
if($ratio <= 2){ //比例对比
if($w > $h){
$w = $this->defaults;
$h = $shearH;
}else{
$w = $shearW;
$h = $this->defaults;
}
}
//条件三 宽或高 > 1280 && 宽高比 <= 2,取较大值等于1280,较小值等比例压缩
if($ratio > 2){
if($w < $this->defaults || $h < $this->defaults){
$w = $w;
$h = $h;
}
//条件四 宽高均 > 1280 && 宽高比 > 2,取较小值等于1280,较大值等比例压缩
if($w > $this->defaults && $h > $this->defaults){
if($w > $h){
$w = $shearW;
$h = $this->defaults;
}else{
$w = $this->defaults;
$h = $shearH;
}
}
}
}
//还有其他操作
return $this->generate($w,$h);
}
//压缩图片
private function generate($width,$height){
list($widths,$heights)= getimagesize($this->url);
$src_im = imagecreatefromjpeg($this->url);
$dst_im = imagecreatetruecolor($width,$height);
imagecopyresized($dst_im,$src_im,0,0,0,0,$width,$height,$widths,$heights);
$this->url = empty($this->name_url) ? $this->url : $this->name_url;
imagejpeg($dst_im,$this->url); //输出压缩后的图片
imagedestroy($dst_im); //释放
imagedestroy($src_im);
return $this->url;
}
}
// new
$a = new compress();
/*
参数一 url: 图片地址 *必须
参数二 name_url:压缩后的图片地址 如: 当前文件夹 ./123.jpg 不填默认替换原图片 *非必须
参数三 width : 自定义宽 (像素) *非必须
参数四 height: 自定义高(像素) *非必须
****注:参数三和参数四必须同时存在,不然程序会自动默认压缩图片;
*/
echo $a->implement('q.jpg');
?>
''''