2019-03-26 16:41:07 1563浏览
有喜欢PHP开发技术的小伙伴通过扣丁学堂官网咨询扣丁学堂的PHP培训老师关于PHP如何进行图像压缩的问题,现在小编整理出来分享给大家,对PHP如何进行图像压缩有疑问的小伙伴来了解一下吧,希望对小伙伴有所帮助。

图像压缩:
对图像进行压
缩处理非常简单,因为就一个函数
参数1:目标图像资源(画布)
参数2:等待压缩图像资源
参数3:目标点的x坐标
参数4:目标点的y坐标
参数5:原图的x坐标
参数6:原图的y坐标
参数7:目的地宽度(画布宽)
参数8:目的地高度(画布高)
参数9:原图宽度
参数10:原图高度
imagecopyresampled($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)
封装的图像压缩类
<?php
/*
* 图像压缩处理类
*/
class Thumb
{
private $_filename; //等待压缩的图像
private $_thumb_path = 'thumb/'; //压缩图像的保存目录
public function __set($p,$v)
{
if(property_exists($this,$p)){
$this -> $p = $v;
}
}
//构造方法初始化需要压缩的图像
public function __construct($file)
{
if(!file_exists($file)){
echo '文件有误,不能压缩';
return;
}
$this -> _filename = $file;
}
//图像压缩处理
function makeThumb($area_w,$area_h)
{
$src_image = imagecreatefrompng($this->_filename);
$res = getimagesize($this->_filename);
echo '<pre>';
var_dump($res);
die;
$dst_x = 0;
$dst_y = 0;
$src_x = 0;
$src_y = 0;
//原图的宽度、高度
$src_w = imagesx($src_image); //获得图像资源的宽度
$src_h = imagesy($src_image); //获得图像资源的高度
if($src_w / $area_w < $src_h/$area_h){
$scale = $src_h/$area_h;
}
if($src_w / $area_w >= $src_h/$area_h){
$scale = $src_w / $area_w;
}
$dst_w = (int)($src_w / $scale);
$dst_h = (int)($src_h / $scale);
$dst_image = imagecreatetruecolor($dst_w,$dst_h);
$color = imagecolorallocate($dst_image,255,255,255);
//将白色设置为透明色
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);
//可以在浏览器直接显示
//header("Content-Type:image/png");
//imagepng($dst_image);
//分目录保存压缩的图像
$sub_path = date('Ymd').'/';
//规范:上传的图像保存到upload目录,压缩的图像保存到thumb目录
if(!is_dir($this -> _thumb_path . $sub_path)){
mkdir($this -> _thumb_path . $sub_path,0777,true);
}
$filename = $this -> _thumb_path . $sub_path.'thumb_'.$this->_filename;
//也可以另存为一个新的图像
imagepng($dst_image,$filename);
return $filename;
}
}
$thumb = new Thumb('upload.jpg');
$thumb -> _thumb_path = 'static/thumb/';
$file = $thumb -> makeThumb(100,50);
// var_dump($file);
最后想要了解更多关于PHP开发方面内容的小伙伴,请关注扣丁学堂PHP培训官网、微信等平台,扣丁学堂IT职业在线学习教育平台为您提供权威的PHP开发视频,PHP培训后的前景无限,行业薪资和未来的发展会越来越好的,扣丁学堂老师精心推出的PHP视频教程定能让你快速掌握PHP从入门到精通开发实战技能。扣丁学堂PHP技术交流群:374332265。
【关注微信公众号获取更多学习资料】 【扫码进入前端H5架构师进阶VIP体验课】