imgUtil.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. <?php
  2. namespace common\components;
  3. use Yii;
  4. class imgUtil
  5. {
  6. //获取图片路径的前缀 ssh 2021.3.12
  7. public static function getPrefix()
  8. {
  9. //$style 1花店 2供货商 3商城
  10. $style = Yii::$app->params['ptStyle'];
  11. if ($style == 2) {
  12. return Yii::$app->params['ghsImgHost'];
  13. } elseif ($style == 1) {
  14. return Yii::$app->params['hdImgHost'];
  15. } elseif ($style == 3) {
  16. return Yii::$app->params['mallImgHost'];
  17. } else {
  18. return Yii::$app->params['hdImgHost'];
  19. }
  20. }
  21. //组合出图片路径 ssh 2021.4.9
  22. public static function groupImg($pic)
  23. {
  24. $prefix = self::getPrefix();
  25. if (empty($pic)) {
  26. return $prefix . 'hhb_small.png';
  27. }
  28. return $prefix . $pic;
  29. }
  30. /**
  31. * OSS 图片水印用的对象路径(桶内相对路径,不要带域名)
  32. * xhGoods.cover 常为 default-img.png,实际对象在 retail/default-img.png
  33. */
  34. public static function normalizeOssObjectPath($pic)
  35. {
  36. $pic = trim((string)$pic);
  37. if ($pic === '') {
  38. return 'retail/default-img.png';
  39. }
  40. if (strpos($pic, 'http://') === 0 || strpos($pic, 'https://') === 0) {
  41. $pic = ltrim(parse_url($pic, PHP_URL_PATH) ?? '', '/');
  42. }
  43. $pic = ltrim($pic, '/');
  44. if ($pic === 'default-img.png' || $pic === 'hhb_small.png') {
  45. return 'retail/default-img.png';
  46. }
  47. return $pic;
  48. }
  49. /**
  50. * 通过 OSS image/info 读取图片宽高(用于海报动态画布)
  51. *
  52. * @return array{0:int,1:int} [width, height]
  53. */
  54. public static function getOssImageSize($objectPath, $prefix = null)
  55. {
  56. $objectPath = self::normalizeOssObjectPath($objectPath);
  57. if ($prefix === null || $prefix === '') {
  58. $prefix = self::getPrefix();
  59. }
  60. $infoUrl = rtrim($prefix, '/') . '/' . $objectPath . '?x-oss-process=image/info';
  61. $context = stream_context_create([
  62. 'http' => [
  63. 'timeout' => 5,
  64. 'ignore_errors' => true,
  65. ],
  66. ]);
  67. $json = @file_get_contents($infoUrl, false, $context);
  68. if ($json === false || $json === '') {
  69. return [0, 0];
  70. }
  71. $data = json_decode($json, true);
  72. if (!is_array($data)) {
  73. return [0, 0];
  74. }
  75. $w = (int)($data['ImageWidth']['value'] ?? 0);
  76. $h = (int)($data['ImageHeight']['value'] ?? 0);
  77. return [$w, $h];
  78. }
  79. }