PHP code example of godzie44 / yii2-image-behavior

1. Go to this page and download the library: Download godzie44/yii2-image-behavior library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

godzie44 / yii2-image-behavior example snippets


 public function behaviors()
    {
        return [
             [
                'class' => \godzie44\yii\behaviors\image\ImageBehavior::className(),

                'imageAttr' => 'avatar', //attribute in model, instance of FileUploaded

                'images' => [ // array of images that we whant to save
                   'default' => ['default' => []],
                   'small' => ['resize' => [150,200]],
                   'fliped' => ['flip' => [30]],
                   'sharped' => ['sharpen' => [30]],
                   'croped' => ['crop' => [30,40,20,10]],
                   'medium-rotate' => ['resize' => [300,400], 'rotate' => [40]],
                ],

                'saveDirectory' => Yii::getAlias('@webroot/uploads/avatars/'),
            ],
            ...
        ];
    }

public function actionProfile() {
        $model =  User::findOne(Yii::$app->user->id);
        if ($model->load(Yii::$app->request->post())) {
            $model->avatar = UploadedFile::getInstance($model, 'avatar');
            $model->save();
        }
        return $this->render('profile', ['model' => $model,]);
    }

class User extends ActiveRecord
{
    public static function tableName()
    {
        return '{{%user}}';
    }

    public function rules()
    {
        return [
            [['name', 'id'], 'safe'],
            [['avatar'], 'file', 'extensions' => 'png, jpg'],
        ];
    }

    public function behaviors()
    {
        return [
            [
                'class' => ImageBehavior::className(),
                'saveDirectory' => Yii::getAlias('@webroot/uploads/avatars/'),
                'imageAttr' => 'avatar',
                'images' => [
                  '_default' => ['default' => []], //save default upload image
                  '_small' => ['resize' => [150,200]], //and save resized copy
                ],
                'options' => [
                    'ifNullBehavior' => ImageBehavior::DO_NOTHING_IF_NULL, 
                    //when avatar attribute contains null, don't need to deleted images and rewrite avatar field
                ]
            ],
        ];
    }


   //getter of resized image
    public function getSmallAvatar(){
        return = $this->getImage('_small');
    }

}

$form = ActiveForm::begin();

echo $form->field($model, 'name')->textInput();

echo Html::img($model->smallAvatar);
echo $form->field($model, 'avatar')->fileInput()->label('change avatar');

echo Html::submitButton('Save', ['class' => 'btn btn-primary']);
ActiveForm::end();