DownloadImageService.php 2.8 KB

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