上传图片
php
//调用方法
//上传公共文件-图片(基础信息)
function public_upload() {
$file = $_FILES['file']; // 获取小程序传来的图片
if (is_uploaded_file($_FILES['file']['tmp_name'])) {
// 把文件转存到你希望的目录(不要使用copy函数)
$uploaded_file = $_FILES['file']['tmp_name'];
// 获取当前日期
$current_date = date("Ymd");
// 动态的创建一个文件夹
$user_path = $_SERVER['DOCUMENT_ROOT'] . "/SO/baseinfo/{$current_date}/";
// 判断该用户文件夹是否已经有这个文件夹
if (!file_exists($user_path)) {
mkdir($user_path, 0777, true);
}
// 获取文件名
$file_true_name = $_FILES['file']['name'];
// 生成随机数
$random_number = mt_rand(1000000000000000, 9999999999999999); // 随机生成16位数字
// 新文件名
$new_file_name = $current_date . '_' . $random_number . '.' . pathinfo($file_true_name, PATHINFO_EXTENSION);
// 文件需要移动到的路径
$move_to_file = $user_path . "/" . $new_file_name;
// 调用压缩图片的方法
if (compress_image($uploaded_file, $move_to_file)) {
$data = [
'code' => 0,
'msg' => '上传成功',
'info' => ['file_path' => "SO/baseinfo/{$current_date}/" . $new_file_name]
];
} else {
$data = ['code' => 1, 'msg' => '压缩或保存图片失败'];
}
// 移动上传的文件
// if (move_uploaded_file($uploaded_file, $move_to_file)) {
// $data = [
// 'code' => 0,
// 'msg' => '上传成功',
// 'info' => ['file_path' => "SO/baseinfo/{$current_date}/" . $new_file_name]
// ];
// } else {
// $data = ['code' => 1, 'msg' => '上传失败'];
// }
} else {
$data = ['code' => 1, 'msg' => '上传失败'];
}
echo json_encode($data, JSON_UNESCAPED_SLASHES);
}
压缩图片方法
php
function compress_image($source_path, $destination_path, $quality = 60, $max_width = 800, $max_height = 800) {
// 获取图像信息
list($width, $height, $type) = getimagesize($source_path);
// 创建图像资源
switch ($type) {
case IMAGETYPE_JPEG:
$image = imagecreatefromjpeg($source_path);
break;
case IMAGETYPE_PNG:
$image = imagecreatefrompng($source_path);
break;
case IMAGETYPE_GIF:
$image = imagecreatefromgif($source_path);
break;
default:
return false; // 不支持的图片格式
}
// 调整图像分辨率
if ($width > $max_width || $height > $max_height) {
$ratio = min($max_width / $width, $max_height / $height);
$new_width = $width * $ratio;
$new_height = $height * $ratio;
$resized_image = imagescale($image, $new_width, $new_height);
imagedestroy($image); // 清除原始图像资源
$image = $resized_image;
}
// 压缩并保存图片
$success = false;
switch ($type) {
case IMAGETYPE_JPEG:
$success = imagejpeg($image, $destination_path, $quality);
break;
case IMAGETYPE_PNG:
// 对于PNG,我们一般不建议更改质量,因为它是一个无损格式
$success = imagepng($image, $destination_path, 9);
break;
case IMAGETYPE_GIF:
$success = imagegif($image, $destination_path);
break;
}
// 清除内存中的图像资源
imagedestroy($image);
return $success;
}