DownloadImageService.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. namespace ln\services;
  3. use think\exception\ValidateException;
  4. class DownloadImageService
  5. {
  6. /**
  7. * 获取即将要下载的图片扩展名
  8. * @param string $url
  9. * @param string $ex
  10. * @return array|string[]
  11. */
  12. public function getImageExtname($url = '', $ex = 'jpg')
  13. {
  14. $_empty = ['file_name' => '', 'ext_name' => $ex];
  15. if (!$url) return $_empty;
  16. if (strpos($url, '?')) {
  17. $_tarr = explode('?', $url);
  18. $url = trim($_tarr[0]);
  19. }
  20. $arr = explode('.', $url);
  21. if (!is_array($arr) || count($arr) <= 1) return $_empty;
  22. $ext_name = trim($arr[count($arr) - 1]);
  23. $ext_name = !$ext_name ? $ex : $ext_name;
  24. return ['file_name' => md5($url) . '.' . $ext_name, 'ext_name' => $ext_name];
  25. }
  26. /**
  27. * @param $url
  28. * @param string $name
  29. * @param int $upload_type
  30. * @return mixed
  31. * @author xaboy
  32. * @day 2020/8/1
  33. */
  34. public function downloadImage($url, $name = '', $upload_type = 1)
  35. {
  36. if (!$name) {
  37. //TODO 获取要下载的文件名称
  38. $downloadImageInfo = $this->getImageExtname($url);
  39. $name = $downloadImageInfo['file_name'];
  40. if (!$name) throw new ValidateException('上传图片不存在');
  41. }
  42. ob_start();
  43. readfile($url);
  44. $content = ob_get_contents();
  45. ob_end_clean();
  46. $size = strlen(trim($content));
  47. if (!$content || $size <= 2) throw new ValidateException('图片流获取失败');
  48. $date_dir = date('Y') . DIRECTORY_SEPARATOR . date('m') . DIRECTORY_SEPARATOR . date('d');
  49. $upload = UploadService::create($upload_type);
  50. if ($upload->to('attach/' . $date_dir)->stream($content, $name) === false) {
  51. throw new ValidateException('图片下载失败');
  52. }
  53. $imageInfo = $upload->getUploadInfo();
  54. $date['path'] = $imageInfo['dir'];
  55. $date['name'] = $imageInfo['name'];
  56. $date['size'] = $imageInfo['size'];
  57. $date['mime'] = $imageInfo['type'];
  58. $date['image_type'] = $upload_type;
  59. $date['is_exists'] = false;
  60. return $date;
  61. }
  62. }