ImageService.php 1.9 KB

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