ImageService.php 1.3 KB

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