DefaultController.php 2.57 KB
<?php

namespace app\wx\modules\user\controllers;

use common\helpers\ImageManager;
use common\helpers\ImageUtils;
use common\models\EngineerProfile;
use domain\toutiao\TtDefaultImageRepository;
use domain\toutiao\TtNewsImageRepository;
use domain\toutiao\TtNewsRepository;
use domain\toutiao\TtType;
use Yii;
use stdClass;

/**
 * 控制器
 */
class DefaultController extends BaseController
{

    /**
     * 首页
     */
    public function actionIndex()
    {
        return $this->render('index');
    }

    /**
     * 上传文件
     * @return string
     */
    public function actionUploadFile()
    {
        $e = new stdClass();
        $e->success = false;
        $e->message = 'ok';
        $userId = 0;

        if (empty($_FILES["file"])) {
            $e->message = '文件为空';
            return $this->renderJson($e);
        }
        if (empty($_FILES["file"]['tmp_name'])) {
            $e->message = '文件为空';
            return $this->renderJson($e);
        }
        $type = $_FILES["file"]["type"];
        $typeArr = explode('/', $type);
        if ('image' !== $typeArr[0]) {
            $e->message = '只能上传 png, jpg 等文件';
            return $this->renderJson($e);
        }

        $dir = Yii::getAlias('@site') . "/tmp";
        $fileArr = explode('.', $_FILES["file"]['name']);
        $tt = time();
        $filename = 'auto_'.$tt.md5($_FILES["file"]['name']).'.'.end($fileArr);
        $minFileName = 'auto_'.$tt.md5($_FILES["file"]['name']).'_min'.'.'.end($fileArr);
        $saveFilePath = $dir.'/'.$filename;
        move_uploaded_file($_FILES["file"]['tmp_name'], $saveFilePath);
        $tmpUrl = $tmpMinFile= $this->site->base_url.'/tmp/'.$filename;
        $imgSource = $this->_imageCreateFromPath($saveFilePath);
        if ($imgSource) {
            ImageUtils::resizeImage($imgSource, 100, 100, $dir.'/'.$minFileName);
            $tmpMinFile = $this->site->base_url.'/tmp/'.$minFileName;
        }

        $e->success = true;
        $e->tmpFile = $filename;
        $e->tmpMinUrl = $tmpMinFile;
        $e->tmpUrl = $tmpUrl;
        $e->message = 'ok';

        return $this->renderJson($e);
    }

    /**
     * @param $imgPath
     * @return null|resource
     */
    private function _imageCreateFromPath($imgPath)
    {
        list($width, $height, $type, $attr) = getimagesize($imgPath);
        switch ($type) {
            case 3: // png
                return imagecreatefrompng($imgPath);
            case 2: // jpeg
                return imagecreatefromjpeg($imgPath);
            default:
                return null;
        }
    }
}