ImageService.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. $curl = new curl\Curl();
  28. $result = $curl->get($url);
  29. $fp = @fopen($fullFileName, 'a');
  30. fwrite($fp, $result);
  31. fclose($fp);
  32. Yii::info('url:' . $url);
  33. //上传oss
  34. oss::uploadImage($fileName,$fullFileName);
  35. $imgInfo = getimagesize($fullFileName);
  36. if (empty($imgInfo) || isset($imgInfo[0]) == false) {
  37. return '';
  38. }
  39. $width = $imgInfo[0];
  40. $height = $imgInfo[1];
  41. //生成小图 200px
  42. $smallWidth = 200;
  43. $smallHeight = ceil((200 * $height) / $width);
  44. if ($width <= 200) {
  45. $smallWidth = $width;
  46. $smallHeight = $height;
  47. }
  48. $smallFullPathFile = $path . $middle . $middleName . '_small.jpg';
  49. Image::thumbnail($fullFileName, $smallWidth, $smallHeight)->save($smallFullPathFile, ['quality' => 100]);
  50. oss::uploadImage($middle . $middleName . '_small.jpg',$smallFullPathFile);
  51. return $fileName;
  52. }
  53. }