Yii: any way to save the images in compressed form?

断了今生、忘了曾经 提交于 2019-12-12 18:21:57

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!