如何从上传的图片中创建拇指图像?
我在控制器中尝试了这个:
<?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]);
}
}
它不起作用。图片已上传,但未创建拇指。
有人可以帮忙吗?
答案 0 :(得分:2)
设置原始和缩略图图像的正确路径,然后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]);
答案 1 :(得分:2)
请尝试使用此代码
$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]);