java上传图片自动压缩图片_java上传图片时压缩图片

/**

* 函数:调整图片尺寸或生成缩略图 v 1.1

* @param $Image 需要调整的图片(含路径)

* @param $Dw 调整时最大宽度;缩略图时的绝对宽度

* @param $Dh 调整时最大高度;缩略图时的绝对高度

* @param $Type 1,调整尺寸; 2,生成缩略图

* @return bool

*/

public function compressImg($image, $Dw, $Dh, $type)

{

if (!file_exists($image)) {

return false;

}

// 如果需要生成缩略图,则将原图拷贝一下重新给$Image赋值(生成缩略图操作)

// 当Type==1的时候,将不拷贝原图像文件,而是在原来的图像文件上重新生成缩小后的图像(调整尺寸操作)

if ($type != 1) {

copy($image, str_replace(".", "_x.", $image));

$image = str_replace(".", "_x.", $image);

}

// 取得文件的类型,根据不同的类型建立不同的对象

$ImgInfo = getimagesize($image);

switch ($ImgInfo[2]) {

case 1:

$Img = @imagecreatefromgif($image);

break;

case 2:

$Img = @imagecreatefromjpeg($image);

Break;

case 3:

$Img = @imagecreatefrompng($image);

break;

}

// 如果对象没有创建成功,则说明非图片文件

if (empty($Img)) {

// 如果是生成缩略图的时候出错,则需要删掉已经复制的文件

if ($type != 1) {

unlink($image);

}

return false;

}

// 如果是执行调整尺寸操作则

if ($type == 1) {

$w = imagesx($Img);

$h = imagesy($Img);

$width = $w;

$height = $h;

if ($width > $Dw) {

$Par = $Dw / $width;

$width = $Dw;

$height = $height * $Par;

if ($height > $Dh) {

$Par = $Dh / $height;

$height = $Dh;

$width = $width * $Par;

}

} elseif ($height > $Dh) {

$Par = $Dh / $height;

$height = $Dh;

$width = $width * $Par;

if ($width > $Dw) {

$Par = $Dw / $width;

$width = $Dw;

$height = $height * $Par;

}

} else {

$width = $Dw;

$height = $Dh;

}

$nImg = imagecreatetruecolor($Dw, $Dh); // 新建一个真彩色画布

$white = imagecolorallocate($nImg, 255, 255, 255);

// 填充白底色

imagefill($nImg, 0, 0, $white);

if ($h / $w > $Dh / $Dw) { // 高比较大

$width = $w * ($Dh / $h);

$IntNW = $Dw - $width;

$Dx = $IntNW / 2;

$Dy = 0;

} else { // 宽比较大

$height = $h * ($Dw / $w);

$IntNH = $Dh - $height;

$Dx = 0;

$Dy = $IntNH / 2;

}

imagecopyresampled($nImg, $Img, $Dx, $Dy, 0, 0, $width, $height, $w, $h); // 重采样拷贝部分图像并调整大小

imagejpeg($nImg, $image); // 以JPEG格式将图像输出到浏览器或文件

return true;

} else { // 如果是执行生成缩略图操作则

$w = imagesx($Img);

$h = imagesy($Img);

$nImg = imagecreatetruecolor($Dw, $Dh);

$white = imagecolorallocate($nImg, 255, 255, 255);

// 填充白底色

imagefill($nImg, 0, 0, $white);

if ($h / $w > $Dh / $Dw) { // 高比较大

$width = $w * ($Dh / $h);

$IntNW = $Dw - $width;

imagecopyresampled($nImg, $Img, $IntNW / 2, 0, 0, 0, $width, $Dh, $w, $h);

} else { // 宽比较大

$height = $h * ($Dw / $w);

$IntNH = $Dh - $height;

imagecopyresampled($nImg, $Img, 0, $IntNH / 2, 0, 0, $Dw, $height, $w, $h);

}

imagejpeg($nImg, $image);

return true;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值