php上传图片并压缩的实现方法
程序员文章站
2024-04-04 16:15:29
...
本文实例讲解了php上传图片并压缩的实现方法,之前一篇《PHP实现图片上传并压缩》已经为大家进行了简单介绍,此次实现上传图片然后按照比例缩略图,指定缩略图的最大高度或者最大宽度,具体内容如下
实现代码:
function _UPLOADPIC($upfile, $maxsize, $updir, $newname = 'date') { if ($newname == 'date') $newname = date ( "Ymdhis" ); //使用日期做文件名 $name = $upfile ["name"]; $type = $upfile ["type"]; $size = $upfile ["size"]; $tmp_name = $upfile ["tmp_name"]; switch ($type) { case 'image/pjpeg' : case 'image/jpeg' : $extend = ".jpg"; break; case 'image/gif' : $extend = ".gif"; break; case 'image/png' : $extend = ".png"; break; } if (emptyempty ( $extend )) { echo ( "警告!只能上传图片类型:GIF JPG PNG" ); exit (); } if ($size > $maxsize) { $maxpr = $maxsize / 1000; echo ( "警告!上传图片大小不能超过" . $maxpr . "K!" ); exit (); } if (move_uploaded_file ( $tmp_name, $updir . $newname . $extend )) { return $updir . $newname . $extend; } } function show_pic_scal($width, $height, $picpath) { $imginfo = GetImageSize ( $picpath ); $imgw = $imginfo [0]; $imgh = $imginfo [1]; $ra = number_format ( ($imgw / $imgh), 1 ); //宽高比 $ra2 = number_format ( ($imgh / $imgw), 1 ); //高宽比 if ($imgw > $width or $imgh > $height) { if ($imgw > $imgh) { $newWidth = $width; $newHeight = round ( $newWidth / $ra ); } elseif ($imgw $per2||$per1==$per2) { //原图长宽比大于或者等于缩略图长宽比,则按照宽度优先 $per=$w/$width; } if($per1$per2) { imagejpeg($temp_img,$savepath, 100); imagedestroy($im); return addBg($savepath,$w,$h,"w"); //宽度优先,在缩放之后高度不足的情况下补上背景 } if($per1==$per2) { imagejpeg($temp_img,$savepath, 100); imagedestroy($im); return $savepath; //等比缩放 } if($per1使用方法
$filename=(_UPLOADPIC($_FILES["upload"],$maxsize,$updir,$newname='date')); $show_pic_scal=show_pic_scal(230, 230, $filename); resize($filename,$show_pic_scal[0],$show_pic_scal[1]);