ImageService.php 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. <?php
  2. namespace common\services;
  3. use common\components\dirUtil;
  4. use common\components\oss;
  5. use common\components\stringUtil;
  6. use linslin\yii2\curl;
  7. use yii\imagine\Image;
  8. //图片相关接口
  9. class ImageService
  10. {
  11. //生成头像
  12. public static function generateAvatar($merchantId, $url)
  13. {
  14. $month = date("Ym");
  15. $date = date("d");
  16. $path = dirUtil::getImgDir();
  17. $middle = "wx/avatar/{$merchantId}/{$month}/{$date}/";
  18. if (!file_exists($path . $middle)) {
  19. mkdir($path . $middle, 0777, true);
  20. }
  21. $rand = stringUtil::uniqueFileName();
  22. $middleName = md5($rand . $url);
  23. $name = $middleName . '.jpg';
  24. $fullFileName = $path . $middle . $name;
  25. $fileName = $middle . $name;
  26. $curl = new curl\Curl();
  27. $result = $curl->get($url);
  28. $fp = @fopen($fullFileName, 'a');
  29. fwrite($fp, $result);
  30. fclose($fp);
  31. //上传oss
  32. oss::uploadImage($middle,$fullFileName);
  33. $imgInfo = getimagesize($fullFileName);
  34. if (empty($imgInfo) || isset($imgInfo[0]) == false) {
  35. return '';
  36. }
  37. $width = $imgInfo[0];
  38. $height = $imgInfo[1];
  39. //生成小图 200px
  40. $smallWidth = 200;
  41. $smallHeight = ceil((200 * $height) / $width);
  42. if ($width <= 200) {
  43. $smallWidth = $width;
  44. $smallHeight = $height;
  45. }
  46. $smallFullPathFile = $path . $middle . $middleName . '_small.jpg';
  47. Image::thumbnail($fullFileName, $smallWidth, $smallHeight)->save($smallFullPathFile, ['quality' => 100]);
  48. return $fileName;
  49. }
  50. }