ImageUploadHandler.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <?php
  2. namespace App\Handlers;
  3. use Image;
  4. class ImageUploadHandler
  5. {
  6. protected $allowed_ext = ["png", "jpg", "gif", 'jpeg'];
  7. public function save($file, $folder, $file_prefix, $max_width = false)
  8. {
  9. // 构建存储的文件夹规则,值如:uploads/images/avatars/201709/21/
  10. // 文件夹切割能让查找效率更高。
  11. $folder_name = "uploads/images/$folder/" . date("Ym", time()) . '/'.date("d", time()).'/';
  12. // 文件具体存储的物理路径,`public_path()` 获取的是 `public` 文件夹的物理路径。
  13. // 值如:/home/vagrant/Code/larabbs/public/uploads/images/avatars/201709/21/
  14. $upload_path = public_path() . '/' . $folder_name;
  15. // 获取文件的后缀名,因图片从剪贴板里黏贴时后缀名为空,所以此处确保后缀一直存在
  16. $extension = strtolower($file->getClientOriginalExtension()) ?: 'png';
  17. // 拼接文件名,加前缀是为了增加辨析度,前缀可以是相关数据模型的 ID
  18. // 值如:1_1493521050_7BVc9v9ujP.png
  19. $filename = $file_prefix . '_' . time() . '_' . str_random(10) . '.' . $extension;
  20. // 如果上传的不是图片将终止操作
  21. if ( ! in_array($extension, $this->allowed_ext)) {
  22. return false;
  23. }
  24. // 将图片移动到我们的目标存储路径中
  25. $file->move($upload_path, $filename);
  26. // 如果限制了图片宽度,就进行裁剪
  27. if ($max_width && $extension != 'gif') {
  28. // 此类中封装的函数,用于裁剪图片
  29. $this->reduseSize($upload_path . '/' . $filename, $max_width);
  30. }
  31. return [
  32. 'path' => config('app.url') . "/$folder_name/$filename"
  33. ];
  34. }
  35. public function reduseSize($file_path, $max_width)
  36. {
  37. // 先实例化,传参是文件的磁盘物理路径
  38. $image = Image::make($file_path);
  39. // 进行大小调整的操作
  40. $image->resize($max_width, null, function ($constraint) {
  41. // 设定宽度是 $max_width,高度等比例双方缩放
  42. $constraint->aspectRatio();
  43. // 防止裁图时图片尺寸变大
  44. $constraint->upsize();
  45. });
  46. // 对图片修改后进行保存
  47. $image->save();
  48. }
  49. }