页面代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>图片压缩上传</title>
</head>
<body>
<!-- action为空表示提交到当前页面 enctype编码格式 -->
<form action="{:url('index/imgThumb')}" method="post" enctype="multipart/form-data">
<!-- 上传文件的名称为img -->
<input type="file" name="img" value="image/*">
<button type="submit" name="button">压缩上传图片</button>
</form>
</body>
</html>
后台php处理方法:
其中$thumb_path.$img_name是缩略图的地址,$compress_path.$img_name是压缩图的地址,$info->getSaveName()是原图地址,可根据自己的业务逻辑自行修改
public function imgThumb() {
//empty():检查一个变量是否为空 / $_FILES数组:接收上传的文件
if(empty($_FILES)){ //提交的文件是否为空
//没有文件则显示提交页面
include 'index.html';
}else{
//获取上传的图片信息
$file = $_FILES['img'];
//原图
//imagecreatefromstring — 从字符串中的图像流新建一图像
//file_get_contents — 将整个文件读入一个字符串 ($file['tmp_name']是图片地址)
$dst_image = imagecreatefromstring(file_get_contents($file['tmp_name']));
//获取图片宽高
list($file_width,$file_height) = getimagesize($file['tmp_name']);
//定义缩略图宽度
$width = 200;
//高度自适应
$height = $file_height / $file_width * $width;
//缩略图
$thumb_img = imagecreatetruecolor($width,$height);
//压缩图
//imagecreatetruecolor — 新建一个真彩色图像
$compress_img = imagecreatetruecolor($file_width,$file_height);
//文件名和后缀以'/'分开 得到一个$suffix数组
$file_type = explode('/',$file['type']);
$img_types = ['jpeg','png','gif'];
//获取图片后缀
$img_type = (in_array($file_type[1],$img_types)) ? $file_type[1] : 'png';
//设置图片上传名称 uniqid基于当前时间微妙数计算的唯一的ID
$img_name = uniqid().'.'.$img_type;
//通过图片类型设置不同格式上传至文件
$fn_name = 'image'.$img_type;
//图片存储路径
$thumb_path = './thumb/'; //缩略图存放路径
$compress_path = './compress/'; //压缩图存放路径
// $orig_path = './orig/'; //原始图存放路径
//该目录是否存在 || 不存在创建该目录
is_dir($thumb_path) || mkdir($thumb_path);
is_dir($compress_path) || mkdir($compress_path);
// is_dir($orig_path) || mkdir($orig_path);
//缩略图
//imagecopyresampled() 将一幅图像中的一块正方形区域拷贝到另一个图像中,平滑地插入像素值,因此,尤其是,减小了图像的大小而仍然保持了极大的清晰度。
//(目标图象,源图象,目标X坐标,目标y坐标,源的X,源的Y,目标宽度,目标高度,源图象的宽度,源图象的高度)
imagecopyresampled($thumb_img,$dst_image,0,0,0,0,$width,$height,$file_width,$file_height);
//上传缩略图片(图片w尺寸200,存储路径)
$fn_name($thumb_img,$thumb_path.$img_name);
//上传压缩图(图片尺寸不变)
imagecopyresampled($compress_img,$dst_image,0,0,0,0,$file_width,$file_height,$file_width,$file_height);
$fn_name($compress_img,$compress_path.$img_name);
//上传原图
// $fn_name($dst_image,$orig_path.$img_name);
$file = request()->file('img');
// $file = $_FILES['img'];
if($file){
$info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
if($info){
// 成功上传后 获取上传信息
// 输出 jpg
echo $info->getExtension();
// 输出 20160820/42a79759f284b767dfcb2a0197904287.jpg
echo $info->getSaveName();
// 输出 42a79759f284b767dfcb2a0197904287.jpg
echo $info->getFilename();
}else{
// 上传失败获取错误信息
echo $file->getError();
}
}
//输出图片
echo "<img src='".$thumb_path.$img_name." ' /> <br>";
echo "<img src='".$compress_path.$img_name." ' /> <br>";
// echo "<img src='".$orig_path.$img_name." ' /> <br>";
}
}