在Yii2中从上传的图像创建缩略图
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在Yii2中从上传的图像创建缩略图相关的知识,希望对你有一定的参考价值。
如何从上传的图像创建拇指图像?
我在我的控制器中试过这个:
<?php
namespace backendcontrollers;
use Yii;
use appmodelsEmployee;
use yiiwebController;
use yiiwebNotFoundHttpException;
use yiifiltersAccessControl;
use yiifiltersVerbFilter;
use yiiwebUploadedFile;
use yiiimagineImage;
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]);
以上是关于在Yii2中从上传的图像创建缩略图的主要内容,如果未能解决你的问题,请参考以下文章