直接使用方法的 Upload($uploadimgfile)
就可以实现上传和压缩操作。
<?php
namespace Home\Controller;
final class Upload
{
//设置文件保存目录
public $uploaddir = "Public/uploadimg/";
//设置允许上传文件的类型
public $type=array("jpg","gif","bmp","jpeg","png");
//获取文件后缀名函数
public function fileext($filename)
{
return substr(strrchr($filename, '.'), 1);
}
//生成随机文件名函数
public function random($length)
{
$hash = 'CRP-'.date("mis");
$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
$max = strlen($chars) - 1;
mt_srand((double)microtime() * 1000000);
for($i = 0; $i < $length; $i++)
{
$hash .= $chars[mt_rand(0, $max)];
}
return $hash;
}
public function Upload($uploadimgfile){
//判断文件类型
if(!in_array(strtolower($this->fileext($uploadimgfile['file']['name'])),$this->type))
{
$text=implode(",",$this->type);
$ret_code=3;//文件类型错误
$page_result=$text;
$retArray = array('ret_code' => $ret_code,'page_result'=>$page_result);
$retJson = json_encode($retArray);
echo $retJson;
return;
}else{
//生成目标文件的文件名
$filename=explode(".",$_FILES['file']['name']);
do
{
$filename[0]=$this->random(8); //设置随机数长度
$name=implode(".",$filename);
$uploadfile=$this->uploaddir.$name;
}while(file_exists($uploadfile));
if(move_uploaded_file($uploadimgfile['file']['tmp_name'],$uploadfile)){
if(is_uploaded_file($uploadimgfile['file']['tmp_name'])){
$ret_code=1;//上传失败
}else {
//上传成功 处理图片大小 如果大于1M 就将图片进行压缩0.5
if($uploadimgfile["file"]['size'] > 1024 * 1024){
list($width,$height,$type)=getimagesize($uploadfile);
$i= 800 / $width;
$new_width = $width*$i;
$new_height =$height*$i;
if($uploadimgfile['file']['type'] == "image/pjpeg" || $uploadimgfile['file']['type'] == "image/jpg" || $uploadimgfile['file']['type'] == "image/jpeg"){
$im = imagecreatefromjpeg($uploadfile);
}elseif($uploadimgfile['file']['type'] == "image/png"){
$im = imagecreatefrompng($uploadfile);
}elseif($uploadimgfile['file']['type'] == "image/gif"){
$im = imagecreatefromgif($uploadfile);
}else{//默认jpg
$im = imagecreatefromjpeg($uploadfile);
}
if($im){
//开始压缩
$image_wp=imagecreatetruecolor($new_width, $new_height);
imagecopyresampled($image_wp, $im, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
imagejpeg($image_wp, $this->uploaddir.'S_'.$name,75);
imagedestroy($image_wp);
}
}
$ret_code=0;
}
}
$retArray = array('ret_code' => $ret_code);
$retJson = json_encode($retArray);
echo $retJson;
}
}
}
?>
832



被折叠的 条评论
为什么被折叠?



