| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455 |
- <?php
- namespace common\services;
- use common\components\dirUtil;
- use common\components\stringUtil;
- use linslin\yii2\curl;
- use yii\imagine\Image;
- //图片相关接口
- class ImageService
- {
- //生成头像
- public static function generateAvatar($merchantId, $url)
- {
- $month = date("Ym");
- $date = date("d");
- $path = dirUtil::getImgDir();
- $middle = "/wx/avatar/{$merchantId}/{$month}/{$date}/";
- if (!file_exists($path . $middle)) {
- mkdir($path . $middle, 0777, true);
- }
- $rand = stringUtil::uniqueFileName();
- $middleName = md5($rand . $url);
- $name = $middleName . '.jpg';
- $fullFileName = $path . $middle . $name;
- $fileName = $middle . $name;
- $curl = new curl\Curl();
- $result = $curl->get($url);
- $fp = @fopen($fullFileName, 'a');
- fwrite($fp, $result);
- fclose($fp);
- $imgInfo = getimagesize($fullFileName);
- if (empty($imgInfo) || isset($imgInfo[0]) == false) {
- return '';
- }
- $width = $imgInfo[0];
- $height = $imgInfo[1];
- //生成小图 200px
- $smallWidth = 200;
- $smallHeight = ceil((200 * $height) / $width);
- if ($width <= 200) {
- $smallWidth = $width;
- $smallHeight = $height;
- }
- $smallFullPathFile = $path . $middle . $middleName . '_small.jpg';
- Image::thumbnail($fullFileName, $smallWidth, $smallHeight)->save($smallFullPathFile, ['quality' => 100]);
- return $fileName;
- }
- }
|