PHPackages                             godzie44/yii2-image-behavior - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Image &amp; Media](/categories/media)
4. /
5. godzie44/yii2-image-behavior

ActiveYii2-extension[Image &amp; Media](/categories/media)

godzie44/yii2-image-behavior
============================

Behavior that will help you to save the modified copy of the uploaded image and give you easy access to them

v1.0.0(10y ago)0331MITPHPPHP &gt;=5.4.0

Since Jun 5Pushed 10y ago1 watchersCompare

[ Source](https://github.com/godzie44/yii2-image-upload-helper-behavior)[ Packagist](https://packagist.org/packages/godzie44/yii2-image-behavior)[ RSS](/packages/godzie44-yii2-image-behavior/feed)WikiDiscussions master Synced 4w ago

READMEChangelog (1)Dependencies (2)Versions (2)Used By (0)

Yii 2 Image Behavior
====================

[](#yii-2-image-behavior)

This behavior will help you to:

- **easy** save uploaded image
- **easy** save modified copy of the initial image by apply modifiers like resize, flip and others. Also, you can apply more modifiers in an arbitrary sequence.
- **get** access to uploaded images
- **delete** images when delete record, update images when update record

Installation
------------

[](#installation)

```
composer require godzie44/yii2-image-behavior
```

Test
----

[](#test)

```
$ codecept run

```

Usage
-----

[](#usage)

In controller.

Just put in image attribute FileUpload object (like in [official guide](http://www.yiiframework.com/doc-2.0/guide-input-file-upload.html)) and call $model-&gt;save() method

In model (example)

```
 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/'),
            ],
            ...
        ];
    }
```

Now in 'saveDirectory' directory we have 6 images with names like "&lt;timestapm&gt;&lt;default/small/fliped/...&gt;.&lt;file extension&gt;"

Get path to this images by calling $model-&gt;getImage('default') - where default is postfix of needed image

Parameters
----------

[](#parameters)

\### Behavior parameters

- **imageAttr** (required, string) Name of model attribute that contains FileUploaded object.
- **images** (required, array\[\]) List of output images. Fields in this array must be format:

    \[string image\_postfix =&gt; \[string modifiers =&gt; array $params, ...\]\]

    where:

    - **image\_postfix** string, postfix of concrete image
    - **modifiers** string, modificator that will be applied to the image. (see modificator list and their params in modificators section)
    - **params** array, params of modificator
- **saveDirectory** (required, string) The directory where the images are saved.
- **options** (optional, array) where:

    - **deleteOldWhenUpdate** (optional, boolean) Default True. True - delete old images when upload new file in existing field, false - don't delete.
    - **ifNullBehavior** (optional, string) Default ImageBehavior::DELETE\_IF\_NULL. ImageBehavior::DELETE\_IF\_NULL - when attribute=NULL old images will be deleted, ImageBehavior::DO\_NOTHING\_IF\_NULL - when attribute=NULL old images dont be deleted and field don be rewrite.

\### Modifiers

- **default** default image, params is empty array \[\].
- **resize** resize image, params \[int width,int height\].
- **flip** flip image, params \[int direction\].
- **sharpen** sharpen image, params \[int amount\].
- **crop** crop image, params \[int width, int height,int offset\_x,int offset\_y\].
- **rotate** rotate image, params \[int degrees\].

You can use this modifiers in any number and combinations.

Simple example of usage (user profile with avatar)
--------------------------------------------------

[](#simple-example-of-usage-user-profile-with-avatar)

In controller

```
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,]);
    }
```

User model like:

```
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');
    }

}
```

In view

```
$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();

```

###  Health Score

27

—

LowBetter than 47% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity12

Limited adoption so far

Community4

Small or concentrated contributor base

Maturity58

Maturing project, gaining track record

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

3677d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/17674942?v=4)[Derevtsov Konstantin](/maintainers/godzie44)[@godzie44](https://github.com/godzie44)

---

Tags

imageBehavioryiiupload image

### Embed Badge

![Health badge](/badges/godzie44-yii2-image-behavior/health.svg)

```
[![Health](https://phpackages.com/badges/godzie44-yii2-image-behavior/health.svg)](https://phpackages.com/packages/godzie44-yii2-image-behavior)
```

###  Alternatives

[yurkinx/yii2-image

Yii2 extension for image manipulating using Kohana Image Library.

64423.2k9](/packages/yurkinx-yii2-image)[raoul2000/yii2-jcrop-widget

This extension is a wrapper for the jQuery Image Cropping Plugin (jcrop)

10262.8k2](/packages/raoul2000-yii2-jcrop-widget)[sjaakp/yii2-illustrated-behavior

ActiveRecord Behavior with associated Widget for Yii2.

423.1k](/packages/sjaakp-yii2-illustrated-behavior)[sadovojav/yii2-image-thumbnail

Yii2 image thumbnail component

2243.5k](/packages/sadovojav-yii2-image-thumbnail)[demi/image

Yii2 behavior for upload image to model

2114.9k](/packages/demi-image)[noam148/yii2-image-resize

A Yii2 component for resizing images (on the fly)

1044.9k7](/packages/noam148-yii2-image-resize)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
