DownloadImageService.php 2.2 KB

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