在 Yii2 中从上传的图片创建缩略图

Create thumbnail from uploaded image in Yii2

如何从上传的图片创建缩略图?

我在我的 控制器中试过这个:

<?php
namespace backend\controllers;

use Yii;
use app\models\Employee;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\AccessControl;
use yii\filters\VerbFilter;
use yii\web\UploadedFile;
use yii\imagine\Image;

public function actionCreate() {
    $model = new Employee();
    $model->added_date_time = date('Y-m-d H:i:s');
    if ($model->load(Yii::$app->request->post())) {
        $model->file = UploadedFile::getInstance($model,'avatar');

        if (!empty($model->file)) {
            $imageName = Yii::$app->security->generateRandomString();
            $model->file->saveAs('uploads/' . $imageName . '.' . $model->file->extension);
            $model->avatar = $imageName . '.' . $model->file->extension;
            $file = 'uploads/' . $imageName . '.' . $model->file->extension;
            Image::thumbnail($file, 200, 200)->save('uploads/thumb/', ['quality' => 80]);
        }
        if ($model->save()) {
            $this->redirect(\Yii::$app->urlManager->createUrl('employee'));
        }
    } else {
        return $this->render('create', ['model' =>  $model]);
    }
}

而且它不起作用。图片已上传,但未创建缩略图。

有人能帮忙吗?

设置原始缩略图图像的正确路径,然后save结果:

$imgPath = Yii::$app->basePath . '/uploads/'; // as an example
$imgName = Yii::$app->security->generateRandomString();
$fileExt = '.' . $model->file->extension;

$originFile = $imgPath . $imgName . $fileExt;
$thumbnFile = $imgPath . $imgName . '-thumb' . $fileExt;

// Generate a thumbnail image
Image::thumbnail($originFile, 200, 200)->save($thumbnFile, ['quality' => 80]);

请尝试使用此代码

$file = Yii::$app->basePath.'/uploads/'.$imageName.'.'.$model->file->extension;
$thumbFile = Yii::$app->basePath.'/uploads/thumb/'.$imageName.'.'.$model->file->extension;
Image::thumbnail($file, 200, 200)->save($thumbFile, ['quality' => 80]);