ImageService.php 1.2 KB

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