问题
I have images having huge size, I want to compress them before they save in database. Here is my controller, is there any way to do this without any extension?
public function actionCreate()
{
$model = new Business;
if (isset($_POST['Business'])) {
$rnd = rand(0, 9999);
$model->attributes = $_POST['Business'];
$uploadedFile = CUploadedFile::getInstance($model, 'image');
$fileName = "{$rnd}-{$uploadedFile}";
$model->image = $fileName;
if ($model->save()) {
$uploadedFile->saveAs(Yii::app()->basePath . '/../img/' . $fileName);
$this->redirect(array('view', 'id' => $model->id));
}
}
$this->render('create', array(
'model' => $model,
));
}
回答1:
1) You need download this extension and connect it in config like in documentation.
2) After upload original file you need just call method resize()
. It is works. I checked it. In your case it will be something like this:
public function actionCreate()
{
$model = new Business;
if (isset($_POST['Business'])) {
$rnd = rand(0, 9999);
$model->attributes = $_POST['Business'];
$uploadedFile = CUploadedFile::getInstance($model, 'image');
$fileName = "{$rnd}-{$uploadedFile}";
$model->image = $fileName;
if ($model->validate()) {
$path = Yii::app()->basePath . '/../img/' . $fileName;
$uploadedFile->saveAs($path);
$image = new EasyImage($path);
$thumbPath = Yii::app()->basePath . '/../thumb/' . $fileName;
$image->resize(100, 100);
$image->save($thumbPath);
$model->save();
$this->redirect(array('view', 'id' => $model->id));
}
}
$this->render('create', array(
'model' => $model,
));
}
来源:https://stackoverflow.com/questions/33807051/yii-any-way-to-save-the-images-in-compressed-form