ImageService.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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 = "/wx/avatar/{$merchantId}/{$month}/{$date}/";
  17. if (!file_exists($path . $middle)) {
  18. mkdir($path . $middle, 0777, true);
  19. }
  20. $rand = stringUtil::uniqueFileName();
  21. $middleName = md5($rand . $url);
  22. $name = $middleName . '.jpg';
  23. $fullFileName = $path . $middle . $name;
  24. $fileName = $middle . $name;
  25. $curl = new curl\Curl();
  26. $result = $curl->get($url);
  27. $fp = @fopen($fullFileName, 'a');
  28. fwrite($fp, $result);
  29. fclose($fp);
  30. $imgInfo = getimagesize($fullFileName);
  31. if (empty($imgInfo) || isset($imgInfo[0]) == false) {
  32. return '';
  33. }
  34. $width = $imgInfo[0];
  35. $height = $imgInfo[1];
  36. //生成小图 200px
  37. $smallWidth = 200;
  38. $smallHeight = ceil((200 * $height) / $width);
  39. if ($width <= 200) {
  40. $smallWidth = $width;
  41. $smallHeight = $height;
  42. }
  43. $smallFullPathFile = $path . $middle . $middleName . '_small.jpg';
  44. Image::thumbnail($fullFileName, $smallWidth, $smallHeight)->save($smallFullPathFile, ['quality' => 100]);
  45. return $fileName;
  46. }
  47. }