fileUtil.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. namespace common\components;
  3. use yii\imagine\Image;
  4. class fileUtil
  5. {
  6. //商家所用的图片上传 ssh 2020.2.26
  7. public static function imgUpload($sjId)
  8. {
  9. header('Content-type:text/html;charset=utf-8');
  10. $base64 = file_get_contents('php://input');
  11. $base64_image_content = str_replace("content=", "", urldecode($base64));
  12. //匹配出图片的格式
  13. if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)) {
  14. $type = $result[2];
  15. $month = date("Ym");
  16. $date = date("d");
  17. $path = dirUtil::getImgUploadDir() . "/{$sjId}/{$month}/{$date}/";
  18. if (!file_exists($path)) {
  19. //检查是否有该文件夹,如果没有就创建,并给予最高权限
  20. mkdir($path, 0700, true);
  21. }
  22. $preFileName = uniqid();
  23. $newFile = $preFileName . ".{$type}";
  24. $fullPathFile = $path . $newFile;
  25. if (file_put_contents($fullPathFile, base64_decode(str_replace($result[1], '', $base64_image_content))) == false) {
  26. util::fail('上传失败!!');
  27. }
  28. $img = "uploads/{$sjId}/{$month}/{$date}/" . $newFile;
  29. $imgInfo = getimagesize($fullPathFile);
  30. $width = $imgInfo[0];
  31. $height = $imgInfo[1];
  32. //如果图片太大,进行压缩,并删除原图
  33. if ($width > 800) {
  34. $newWidth = 800;
  35. $newHeight = ceil((800 * $height) / $width);
  36. $preFileName = stringUtil::uniqueFileName();
  37. $newFile = $preFileName . ".{$type}";
  38. $newFullPathFile = $path . $newFile;
  39. Image::thumbnail($fullPathFile, $newWidth, $newHeight)->save($newFullPathFile, ['quality' => 100]);
  40. $width = $newWidth;
  41. $height = $newHeight;
  42. $img = "uploads/{$sjId}/{$month}/{$date}/" . $newFile;
  43. unlink($fullPathFile);
  44. $fullPathFile = $newFullPathFile;
  45. }
  46. //上传oss 2021.3.18 lqh
  47. oss::uploadImage($img,$fullPathFile);
  48. //生成小图 300px
  49. $smallWidth = 300;
  50. $smallHeight = ceil(($smallWidth * $height) / $width);
  51. $smallFullPathFile = $path . $preFileName . '_small.' . $type;
  52. Image::thumbnail($fullPathFile, $smallWidth, $smallHeight)->save($smallFullPathFile, ['quality' => 100]);
  53. $data = business::formatUploadImg($img);
  54. $data['shortUrl'] = $img;
  55. return $data;
  56. }
  57. util::fail('上传失败!');
  58. }
  59. }