图片上传并进行压缩的功能,PHP代码,测试完美无错
发表:紫石头原创模板堂 发表时间:2017-04-11 13:53:37 阅读:427次
一个图片压缩函数,紫石头原创模板堂亲测无错,发布出来供大家使用。试了很多代码都是报错,这个代码不错,JPG、PNG、gif图片格式都想到了。
这样调用:
$im='..'.$src;//需要用相对路径
$name='..'.$src;//保存路径,也是需要用相对路径
$filetype=$_FILES['baidi_pic']['type'];//类型
thumbImage($im,1000,1000,$name,$_FILES['baidi_pic']['type']);
//压缩图片
function thumbImage($im,$maxwidth,$maxheight,$name,$filetype)
{
switch ($filetype) {
case 'image/pjpeg':
case 'image/jpeg':
$im = imagecreatefromjpeg($im); //PHP图片处理系统函数
break;
case 'image/gif':
$im = imagecreatefromgif($im);
break;
case 'image/png':
$im = imagecreatefrompng($im);
break;
case 'image/wbmp':
$im = imagecreatefromwbmp($im);
break;
}
$resizewidth_tag = $resizeheight_tag = false;
$pic_width = imagesx($im);
$pic_height = imagesy($im);
if(($maxwidth && $pic_width > $maxwidth) || ($maxheight && $pic_height > $maxheight))
{
$resizeheight_tag = false;
if($maxwidth && $pic_width>$maxwidth)
{
$widthratio = $maxwidth / $pic_width;
$resizewidth_tag = true;
}
if($maxheight && $pic_height>$maxheight)
{
$heightratio = $maxheight / $pic_height;
$resizeheight_tag = true;
}
if($resizewidth_tag && $resizeheight_tag)
{
if($widthratio < $heightratio)
$ratio = $widthratio;
else
$ratio = $heightratio;
}
if($resizewidth_tag && !$resizeheight_tag)
$ratio = $widthratio;
if($resizeheight_tag && !$resizewidth_tag)
$ratio = $heightratio;
$newwidth = $pic_width * $ratio;
$newheight = $pic_height * $ratio;
if(function_exists("imagecopyresampled"))
{
$newim = imagecreatetruecolor($newwidth,$newheight);//PHP图片处理系统函数
imagecopyresampled($newim,$im,0,0,0,0,$newwidth,$newheight,$pic_width,$pic_height);//PHP图片处理系统函数
}
else
{
$newim = imagecreate($newwidth,$newheight);
imagecopyresized($newim,$im,0,0,0,0,$newwidth,$newheight,$pic_width,$pic_height);
}
switch ($filetype) {
case 'image/pjpeg' :
case 'image/jpeg' :
$result = imagejpeg($newim,$name);
break;
case 'image/gif' :
$result = imagegif($newim,$name);
break;
case 'image/png' :
$result = imagepng($newim,$name);
break;
case 'image/wbmp' :
$result = imagewbmp($newim,$name);
break;
}
imagedestroy($newim);
}
else
{
switch ($filetype) {
case 'image/pjpeg' :
case 'image/jpeg' :
$result = imagejpeg($im,$name);
break;
case 'image/gif' :
$result = imagegif($im,$name);
break;
case 'image/png' :
$result = imagepng($im,$name);
break;
case 'image/wbmp' :
$result = imagewbmp($im,$name);
break;
}
}
return $result;
}
十六年网站建设相关经验
一站式为您提供网站相关服务
欢迎扫码咨询