ImageService.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. use Yii;
  9. //图片相关接口
  10. class ImageService
  11. {
  12. //生成头像
  13. public static function generateAvatar($sjId, $url)
  14. {
  15. $month = date("Ym");
  16. $date = date("d");
  17. $path = dirUtil::getImgDir();
  18. $sjId = substr(md5($url), 0, 5);
  19. $middle = "wx/avatar/{$sjId}/{$month}/{$date}/";
  20. if (!file_exists($path . $middle)) {
  21. mkdir($path . $middle, 0777, true);
  22. }
  23. $rand = stringUtil::uniqueFileName();
  24. $middleName = md5($rand . $url);
  25. $name = $middleName . '.jpg';
  26. $fullFileName = $path . $middle . $name;
  27. $fileName = $middle . $name;
  28. $respond = oss::fileExist($fileName);
  29. if ($respond) {
  30. Yii::info('url' . $url . ' 已经创建过了');
  31. return $fileName;
  32. }
  33. $curl = new curl\Curl();
  34. $result = $curl->get($url);
  35. $fp = @fopen($fullFileName, 'a');
  36. fwrite($fp, $result);
  37. fclose($fp);
  38. Yii::info('url:' . $url);
  39. //上传oss
  40. oss::uploadImage($fileName, $fullFileName);
  41. $imgInfo = getimagesize($fullFileName);
  42. if (empty($imgInfo) || isset($imgInfo[0]) == false) {
  43. return '';
  44. }
  45. $width = $imgInfo[0];
  46. $height = $imgInfo[1];
  47. //生成小图 200px
  48. $smallWidth = 200;
  49. $smallHeight = ceil((200 * $height) / $width);
  50. if ($width <= 200) {
  51. $smallWidth = $width;
  52. $smallHeight = $height;
  53. }
  54. $smallFullPathFile = $path . $middle . $middleName . '_small.jpg';
  55. Image::thumbnail($fullFileName, $smallWidth, $smallHeight)->save($smallFullPathFile, ['quality' => 100]);
  56. oss::uploadImage($middle . $middleName . '_small.jpg', $smallFullPathFile);
  57. return $fileName;
  58. }
  59. }