ImageService.php 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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::getImgDir();
  16. $middle = "/uploads/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. if (empty($imgInfo) || isset($imgInfo[0]) == false) {
  31. return '';
  32. }
  33. $width = $imgInfo[0];
  34. $height = $imgInfo[1];
  35. //生成小图 200px
  36. $smallWidth = 200;
  37. $smallHeight = ceil((200 * $height) / $width);
  38. if ($width <= 200) {
  39. $smallWidth = $width;
  40. $smallHeight = $height;
  41. }
  42. $smallFullPathFile = $path . $middle . $middleName . '_small.jpg';
  43. Image::thumbnail($fullFileName, $smallWidth, $smallHeight)->save($smallFullPathFile, ['quality' => 100]);
  44. return $fileName;
  45. }
  46. }