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