php压缩图片代码
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
php压缩图⽚代码
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2019/10/25
* Time: 14:36
*/
class Imgcompress
{
private $src;
private $image;
private $imageinfo;
private $percent = 0.5;
/**
* 图⽚压缩
* @param string $src 源图
* @param float $percent 压缩⽐例
*/
public function __construct($src, $percent = 1)
{
$this->src = $src;
$this->percent = $percent;
}
/** ⾼清压缩图⽚
* @param string $saveName 提供图⽚名(可不带扩展名,⽤源图扩展名)⽤于保存。
或不提供⽂件名直接显⽰
*/
public function compressImg($saveName = '')
{
$this->_openImage();
if (!empty($saveName)) $this->_saveImage($saveName); //保存
else $this->_showImage();
}
/**
* 内部:打开图⽚
*/
private function _openImage()
{
list($width, $height, $type, $attr) = getimagesize($this->src);
$this->imageinfo = array(
'width' => $width,
'height' => $height,
'type' => image_type_to_extension($type, false),
'attr' => $attr
);
$fun = "imagecreatefrom" . $this->imageinfo['type'];
$this->image = $fun($this->src);
$this->_thumpImage();
}
/**
* 内部:操作图⽚
*/
private function _thumpImage()
{
$new_width = $this->imageinfo['width'] * $this->percent;
$new_height = $this->imageinfo['height'] * $this->percent;
$image_thump = imagecreatetruecolor($new_width, $new_height);
//将原图复制带图⽚载体上⾯,并且按照⼀定⽐例压缩,极⼤的保持了清晰度
imagecopyresampled($image_thump, $this->image, 0, 0, 0, 0, $new_width, $new_height, $this->imageinfo['width'], $this->imageinfo['height']); imagedestroy($this->image);
$this->image = $image_thump;
}
/**
* 输出图⽚:保存图⽚则⽤saveImage()
*/
private function _showImage()
{
header('Content-Type: image/' . $this->imageinfo['type']);
$funcs = "image" . $this->imageinfo['type'];
$funcs($this->image);
}
/**
* 保存图⽚到硬盘:
* @param string $dstImgName 1、可指定字符串不带后缀的名称,使⽤源图扩展名。
2、直接指定⽬标图⽚名带扩展名。
*/
private function _saveImage($dstImgName)
{
if (empty($dstImgName)) return false;
$allowImgs = array('.jpg', '.jpeg', '.png', '.bmp', '.wbmp', '.gif'); //如果⽬标图⽚名有后缀就⽤⽬标图⽚扩展名后缀,如果没有,则⽤源图的扩展名 $dstExt = strrchr($dstImgName, ".");
$sourseExt = strrchr($this->src, ".");
if (!empty($dstExt)) $dstExt = strtolower($dstExt);
if (!empty($sourseExt)) $sourseExt = strtolower($sourseExt);
//有指定⽬标名扩展名
if (!empty($dstExt) && in_array($dstExt, $allowImgs)) {
$dstName = $dstImgName;
} elseif (!empty($sourseExt) && in_array($sourseExt, $allowImgs)) {
$dstName = $dstImgName . $sourseExt;
} else {
$dstName = $dstImgName . $this->imageinfo['type'];
}
$funcs = "image" . $this->imageinfo['type'];
$funcs($this->image, $dstName);
}
/**
* 销毁图⽚
*/
public function __destruct()
{
imagedestroy($this->image);
}
}
测试代码如下
<?php
require_once 'Imgcompress.php';
$pic = dirname(__FILE__).'/test.jpg';
$img = new Imgcompress($pic,1);
$img->compressImg($pic);。