Code Monkey home page Code Monkey logo

yii2-widget-cropbox's Introduction

yii2-widget-cropbox

Latest Stable Version Total Downloads License Build Status Coverage Status

This is Yii2 widget wrapper for js-cropbox.

Demo and documentation of plugin

js-cropbox Demo

js-cropbox README

Installation

The preferred way to install this extension is through composer.

Either run

$ php composer.phar require --prefer-dist bupy7/yii2-widget-cropbox "*"

or add

"bupy7/yii2-widget-cropbox": "*"

to the require section of your composer.json file.

If you use v4.1.2 then go to v4.1.2.

If you use v3.0.1 then go to v3.0.1.

If you use v2.2 then go to v2.2.

If you use v1.0 then go to v1.0.

Options

$pluginOptions

Contain configuration of js-cropbox wrapper.

(array) $variants: Variants of cropping image.

More info: https://github.com/bupy7/js-cropbox#object-variants

(array) [$selectors]: CSS selectors for attach events of cropbox.
  • (string) fileInput
  • (string) btnCrop
  • (string) btnReset
  • (string) btnScaleIn
  • (string) btnScaleOut
  • (string) croppedContainer
  • (string) croppedDataInput
  • (string) messageContainer
(array) [$messages]: Alert messages for each a variant.

Usage

For example, I will use Imagine extensions for Yii2 https://github.com/yiisoft/yii2-imagine . You can use something other.

Add in action to your controller:

...

if ($model->load(Yii::$app->request->post()))
{   
    $model->image = \yii\web\UploadedFile::getInstance($model, 'image');
    
    if ($model->save()) 
    {
        return $this->redirect(['index']);
    }
}

...

Add to your view:

use bupy7\cropbox\CropboxWidget;

$form = ActiveForm::begin([
    'options' => ['enctype'=>'multipart/form-data'],
]);

...

echo $form->field($model, 'image')->widget(CropboxWidget::className(), [
    'croppedDataAttribute' => 'crop_info',
]);

...

Add to your model:

...

use yii\helpers\FileHelper;
use yii\imagine\Image;
use yii\helpers\Json;
use Imagine\Image\Box;
use Imagine\Image\Point;

...

public $image;
public $crop_info;

...

public function rules()
{
    ...
    
    [
        'image', 
        'image', 
        'extensions' => ['jpg', 'jpeg', 'png', 'gif'],
        'mimeTypes' => ['image/jpeg', 'image/pjpeg', 'image/png', 'image/gif'],
    ],
    ['crop_info', 'safe'],
    
    ...
}

...

public function afterSave($insert, $changedAttributes)
{
    ...

    // open image
    $image = Image::getImagine()->open($this->image->tempName);

    // rendering information about crop of ONE option 
    $cropInfo = Json::decode($this->crop_info)[0];
    $cropInfo['dWidth'] = (int)$cropInfo['dWidth']; //new width image
    $cropInfo['dHeight'] = (int)$cropInfo['dHeight']; //new height image
    $cropInfo['x'] = $cropInfo['x']; //begin position of frame crop by X
    $cropInfo['y'] = $cropInfo['y']; //begin position of frame crop by Y
    // Properties bolow we don't use in this example
    //$cropInfo['ratio'] = $cropInfo['ratio'] == 0 ? 1.0 : (float)$cropInfo['ratio']; //ratio image. 
    //$cropInfo['width'] = (int)$cropInfo['width']; //width of cropped image
    //$cropInfo['height'] = (int)$cropInfo['height']; //height of cropped image
    //$cropInfo['sWidth'] = (int)$cropInfo['sWidth']; //width of source image
    //$cropInfo['sHeight'] = (int)$cropInfo['sHeight']; //height of source image

    //delete old images
    $oldImages = FileHelper::findFiles(Yii::getAlias('@path/to/save/image'), [
        'only' => [
            $this->id . '.*',
            'thumb_' . $this->id . '.*',
        ], 
    ]);
    for ($i = 0; $i != count($oldImages); $i++) {
        @unlink($oldImages[$i]);
    }

    //saving thumbnail
    $newSizeThumb = new Box($cropInfo['dWidth'], $cropInfo['dHeight']);
    $cropSizeThumb = new Box(200, 200); //frame size of crop
    $cropPointThumb = new Point($cropInfo['x'], $cropInfo['y']);
    $pathThumbImage = Yii::getAlias('@path/to/save/image') 
        . '/thumb_' 
        . $this->id 
        . '.' 
        . $this->image->getExtension();  

    $image->resize($newSizeThumb)
        ->crop($cropPointThumb, $cropSizeThumb)
        ->save($pathThumbImage, ['quality' => 100]);

    //saving original
    $this->image->saveAs(
        Yii::getAlias('@path/to/save/image') 
        . '/' 
        . $this->id 
        . '.' 
        . $this->image->getExtension()
    );
}

...

Configuration

Preview exist image of item

If you want to show uploaded and cropped image, you must add following code:

echo $form->field($model, 'image')->widget(CropboxWidget::className(), [

    ...

    'croppedImagesUrl' => [
        'url/to/small/image'
    ],
    'originalImageUrl' => 'url/to/original/image',
]);

If you will click on preview image you see original image.

Crop with save real size of image

Difference from previous methods in that we don't resize image before crop it. We cropped image as we see it in editor box with saving real size.

For this we will use property ratio from $cropInfo.

$cropInfo = Json::decode($this->crop_info)[0];
$cropInfo['dWidth'] = (int)$cropInfo['dWidth'];
$cropInfo['dHeight'] = (int)$cropInfo['dHeight'];
$cropInfo['x'] = abs($cropInfo['x']);
$cropInfo['y'] = abs($cropInfo['y']);
$cropInfo['ratio'] = $cropInfo['ratio'] == 0 ? 1.0 : (float)$cropInfo['ratio'];
 
$image = Image::getImagine()->open($this->image->tempName);
 
$cropSizeLarge = new Box(200 / $cropInfo['ratio'], 200 / $cropInfo['ratio']);
$cropPointLarge = new Point($cropInfo['x'] / $cropInfo['ratio'], $cropInfo['y'] / $cropInfo['ratio']);
$pathLargeImage = Yii::getAlias('path/to/save') . '/' . $this->id . '.' . $this->image->getExtension();
 
$image->crop($cropPointLarge, $cropSizeLarge)
    ->save($pathLargeImage, ['quality' => $module->qualityLarge]);

Cropping more once option

If you will set few veriants crop on plugin you need make following:

In model:

...

public function afterSave($insert, $changedAttributes)
{
    ...
    
    // open image
    $image = Image::getImagine()->open($this->image->tempName);
    
    $variants = [
        [
            'width' => 150,
            'height' => 150,
        ],
        [
            'width' => 350,
            'height' => 200,
        ],
    ];
    for($i = 0; $i != count(Json::decode($this->crop_info)); $i++) {
        $cropInfo = Json::decode($this->crop_info)[$i];
        $cropInfo['dWidth'] = (int)$cropInfo['dWidth']; //new width image
        $cropInfo['dHeight'] = (int)$cropInfo['dHeight']; //new height image
        $cropInfo['x'] = abs($cropInfo['x']); //begin position of frame crop by X
        $cropInfo['y'] = abs($cropInfo['y']); //begin position of frame crop by Y
        //$cropInfo['ratio'] = $cropInfo['ratio'] == 0 ? 1.0 : (float)$cropInfo['ratio']; //ratio image. We don't use in this example

        //delete old images
        $oldImages = FileHelper::findFiles(Yii::getAlias('@path/to/save/image'), [
            'only' => [
                $this->id . '.' . $i . '.*',
                'thumb_' . $this->id . '.' . $i . '.*',
            ], 
        ]);
        for ($j = 0; $j != count($oldImages); $j++) {
            @unlink($oldImages[$j]);
        }

        //saving thumbnail
        $newSizeThumb = new Box($cropInfo['dWidth'], $cropInfo['dHeight']);
        $cropSizeThumb = new Box($variants[$i]['width'], $variants[$i]['height']); //frame size of crop
        $cropPointThumb = new Point($cropInfo['x'], $cropInfo['y']);
        $pathThumbImage = Yii::getAlias('@path/to/save/image') . '/thumb_' . $this->id . '.' . $i . '.' . $this->image->getExtension();  

        $image->copy()
            ->resize($newSizeThumb)
            ->crop($cropPointThumb, $cropSizeThumb)
            ->save($pathThumbImage, ['quality' => 100]);

        //saving original
        $this->image->saveAs(Yii::getAlias('@path/to/save/image') . $this->id . '.' . $i . '.' . $this->image->getExtension());
    }
}

...

Use resizing

If you want use resizing you need pointer min and max size of image in variants of pluginOptions.

In model:

// open image
$image = Image::getImagine()->open($this->image->tempName);

// rendering information about crop of ONE option 
$cropInfo = Json::decode($this->crop_info)[0];
$cropInfo['dWidth'] = (int)$cropInfo['dWidth']; //new width image
$cropInfo['dHeight'] = (int)$cropInfo['dHeight']; //new height image
$cropInfo['x'] = abs($cropInfo['x']); //begin position of frame crop by X
$cropInfo['y'] = abs($cropInfo['y']); //begin position of frame crop by Y
$cropInfo['width'] = (int)$cropInfo['width']; //width of cropped image
$cropInfo['height'] = (int)$cropInfo['height']; //height of cropped image
// Properties bolow we don't use in this example
//$cropInfo['ratio'] = $cropInfo['ratio'] == 0 ? 1.0 : (float)$cropInfo['ratio']; //ratio image. 

//delete old images
$oldImages = FileHelper::findFiles(Yii::getAlias('@path/to/save/image'), [
    'only' => [
        $this->id . '.*',
        'thumb_' . $this->id . '.*',
    ], 
]);
for ($i = 0; $i != count($oldImages); $i++) {
    @unlink($oldImages[$i]);
}

//saving thumbnail
$newSizeThumb = new Box($cropInfo['dWidth'], $cropInfo['dHeight']);
$cropSizeThumb = new Box($cropInfo['width'], $cropInfo['height']); //frame size of crop
$cropPointThumb = new Point($cropInfo['x'], $cropInfo['y']);
$pathThumbImage = Yii::getAlias('@path/to/save/image') . '/thumb_' . $this->id . '.' . $this->image->getExtension();  

$image->resize($newSizeThumb)
    ->crop($cropPointThumb, $cropSizeThumb)
    ->save($pathThumbImage, ['quality' => 100]);
    
//saving original
$this->image->saveAs(Yii::getAlias('@path/to/save/image') . $this->id . '.' . $this->image->getExtension());

License

yii2-widget-cropbox is released under the BSD 3-Clause License.

yii2-widget-cropbox's People

Contributors

alexjeen avatar bryant1410 avatar bupy7 avatar manoelt avatar toriphes avatar veyselsahin avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

yii2-widget-cropbox's Issues

Размер области редактирования изображения

Добрый день!

А будет добавлена возможность задавать параметры размера области редактирования?

просто сейчас получается большие по разрешению фотографии уж очень долго колесиком скролить до нужных размеров.

Как использовать ratio?

Здравствуйте, хотел бы чтобы область для обрезания была с определенным соотношением сторон, поддерживает ли плагин такую возможность? Если нет, очень хотелось бы чтобы добавили. Заранее спасибо.

Set width and height of cropbox

Is there a way to set the width and height of the cropbox and to not make it resizeable? I saw the properties in the .js file, but I wonder if there's another way than editing the file.

Undefined index: dh

I'm using 2.2 version of your extension.

If I browsed the image in my form and click on save button without clicking on crop button, I got this error Undefined index: dh,
There should be some kind of handler , if crop button not clicked, then upload only image don't create thumbnail or create thumbnail of original image.

Thank you.

Change Event Listener

For a project that I'm currently working on I use the cropbox, and I'm really loving it so far.

On little problem that I do have, is that whenever the plugin is enabled, the on(change) event listener behaves strangly on my select box, it has a size attribute, and once it has that, the on change does not register mouse clicks anymore, this problem is over when I desable the loading of this plugin.

Does somebody have a work around for this, ore a fix?

Undefined index: dHeight

Hello,

When trying to save an image I'm getting this error. Note: I'm using yii2-user and adding the image to the profile form.

My model:

namespace app\models;

use dektrium\user\models\Profile as BaseProfile;
use yii\helpers\FileHelper;
use yii\imagine\Image;
use yii\helpers\Json;
use Imagine\Image\Box;
use Imagine\Image\Point;

class Profile extends BaseProfile {

	public $picture;
	public $crop_info;

    public function rules() {
        $rules = parent::rules();
        $rules[] = [
			        'picture', 
			        'image', 
			        'extensions' => ['jpg', 'jpeg', 'png', 'gif'],
			        'mimeTypes' => ['image/jpeg', 'image/pjpeg', 'image/png', 'image/gif'],
			    ];
        $rules[] = ['crop_info', 'safe'];
        return $rules;
    }

    public function afterSave($insert, $changedAttributes)
	{
	    $picture = Image::getImagine()->open($this->picture->tempName);

	    $cropInfo = Json::decode($this->crop_info)[0];

	    $cropInfo['dWidth'] = (int)$cropInfo['dWidth']; //new width image
	    $cropInfo['dHeight'] = (int)$cropInfo['dHeight']; //new height image
	    $cropInfo['x'] = $cropInfo['x']; //begin position of frame crop by X
	    $cropInfo['y'] = $cropInfo['y']; //begin position of frame crop by Y

	    //delete old images
	    $oldImages = FileHelper::findFiles(Yii::getAlias('@web/users'), [
	        'only' => [
	            $this->id . '.*',
	            'thumb_' . $this->id . '.*',
	        ], 
	    ]);
	    for ($i = 0; $i != count($oldImages); $i++) {
	        @unlink($oldImages[$i]);
	    }

	    //saving thumbnail
	    $newSizeThumb = new Box($cropInfo['dWidth'], $cropInfo['dHeight']);
	    $cropSizeThumb = new Box(200, 200); //frame size of crop
	    $cropPointThumb = new Point($cropInfo['x'], $cropInfo['y']);
	    $pathThumbImage = Yii::getAlias('@web/users') 
	        . '/thumb_' 
	        . $this->id 
	        . '.' 
	        . $this->picture->getExtension();  

	    $picture->resize($newSizeThumb)
	        ->crop($cropPointThumb, $cropSizeThumb)
	        ->save($pathThumbImage, ['quality' => 100]);

	    //saving original
	    $this->picture->saveAs(
	        Yii::getAlias('@web/users') 
	        . '/' 
	        . $this->id 
	        . '.' 
	        . $this->picture->getExtension()
	    );
	    parent::afterSave($insert, $changedAttributes);
	}

}

My View:

<?php
                    echo $form->field($model, 'picture')->widget(CropboxWidget::className(), [
                        'croppedDataAttribute' => 'crop_info',
                        'pluginOptions' => [
                            'variants' => [
                                ['width' => 160,
                                'height' => 160,
                                'minWidth' => 160,
                                'minHeight' => 160,
                                'maxWidth' => 500,
                                'maxHeight' => 500,],
                            ],
                            'messages' => [
                                ['Ajuste a imagem.'],
                            ]
                        ],
                    ]);
                ?>

My Controller:

<?php

namespace app\controllers;

use dektrium\user\controllers\SettingsController as BaseSettingsController;

class SettingsController extends BaseSettingsController
{
    public function actionProfile()
    {
        $model = $this->finder->findProfileById(\Yii::$app->user->identity->getId());
        if ($model == null) {
            $model = \Yii::createObject(Profile::className());
            $model->link('user', \Yii::$app->user->identity);
        }
        $event = $this->getProfileEvent($model);
        $this->performAjaxValidation($model);
        $this->trigger(self::EVENT_BEFORE_PROFILE_UPDATE, $event);
        if ($model->load(\Yii::$app->request->post())) {
        	//die(print_r(\Yii::$app->request, true));

        	$model->picture = \yii\web\UploadedFile::getInstance($model, 'picture');

			if ($model->save()){
	            \Yii::$app->getSession()->setFlash('success', \Yii::t('user', 'Your profile has been updated'));
	            $this->trigger(self::EVENT_AFTER_PROFILE_UPDATE, $event);
	            return $this->refresh();
	        }

        }
        return $this->render('profile', [
            'model' => $model,
        ]);
    }
}```

how to resize/crop and save cropped image

thanks.. this is a smart tools, but i found some trouble for my case:

  1. how to resize/crop and save cropped image without use models (using controller)
  2. i got error in model (function aftersave(){} )
    $image = Image::getImagine()->open($this->image->tempName);
    • what the meaning of tempName?

error say: PHP Notice – yii\base\ErrorException
Trying to get property of non-object

Class 'bupy7\cropbox\Cropbox' not found

i m using version v3.0.1.
in my view i am including

use bupy7\cropbox\Cropbox;

<?php $form = ActiveForm::begin([
                'options' => ['enctype'=>'multipart/form-data'],
            ]); ?>
  <?php echo $form->field($model, 'image')->widget(Cropbox::className(), [
                'attributeCropInfo' => 'crop_info',
                'optionsCropbox' => [
                    'boxWidth' => 400,
                    'boxHeight' => 300,
                    'cropSettings' => [
                        [
                            'width' => 350,
                            'height' => 200,
                        ],
                    ],
                ],
            ]); ?>

but it gives me the error

PHP Fatal Error – yii\base\ErrorException

Class 'bupy7\cropbox\Cropbox' not found

How to save the cropped picture for beginner?

Here's my controller

public function actionCreate()
    {
        $model = new Carousel();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {			
			 $model->images = UploadedFile::getInstance($model, 'images');  
			$model->path = '../web/images/banners/'. $model->images->baseName . '_' . time() . '.' . $model->images->extension;   	 	
			$model->save();			 
			$model->images->saveAs('images/banners/' . $model->images->baseName . '_' . time() . '.' . $model->images->extension); 
            return $this->redirect(['carousel/index']);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }`
```

My model

   ```
 public $images;
    public $crop_info;
    public static function tableName()
    {
        return 'carousel';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id'], 'integer'],
            [['path', 'heading', 'content', 'link'], 'string'],
			[['images'], 'file', 'extensions' => 'png, jpg, gif, jpeg', 'maxSize'=>1024*1024*10],
			['crop_info', 'safe'],
        ];
    }`
`
```

My View

` <?= $form->field($model, 'images')->widget(Cropbox::className(), [
    'attributeCropInfo' => 'crop_info',
]);?>`

With this I can only save the original picture not the cropped picture. I could not figure out how to save the cropped picture. Please help me with this.

Thank you!

File does not exist.

Hi , Thank for your sharing, i had met some problem, can help me fix ? Thank you!

(view)

field($model,'member_profile')->widget(Cropbox::classname(),[ 'attributeCropInfo' => 'crop_info', ] ); ?>

(model)
public function afterSave($insert, $changedAttributes)
{
// open image
$image = Image::getImagine()->open($this->image->tempName);
$cropInfo = Json::decode($this->crop_info)[0];
$cropInfo['dWidth'] = (int)$cropInfo['dWidth'];
$cropInfo['dHeight'] = (int)$cropInfo['dHeight'];
$cropInfo['x'] = $cropInfo['x'];
$cropInfo['y'] = $cropInfo['y'];
$oldImages = FileHelper::findFiles(Yii::getAlias('@path/to/save/image'), [
'only' => [
$this->id . '.',
'thumb_' . $this->id . '.
',
],
]);
for ($i = 0; $i != count($oldImages); $i++) {
@Unlink($oldImages[$i]);
}
//saving thumbnail
$newSizeThumb = new Box($cropInfo['dWidth'], $cropInfo['dHeight']);
$cropSizeThumb = new Box(200, 200); //frame size of crop
$cropPointThumb = new Point($cropInfo['x'], $cropInfo['y']);
$pathThumbImage = Yii::getAlias('@path/to/save/image')
. '/thumb_'
. $this->id
. '.'
. $this->image->getExtension();

$image->resize($newSizeThumb)
    ->crop($cropPointThumb, $cropSizeThumb)
    ->save($pathThumbImage, ['quality' => 100]);

//saving original
$this->image->saveAs(
    Yii::getAlias('@path/to/save/image') 
    . '/' 
    . $this->id 
    . '.' 
    . $this->image->getExtension()
);

}

(controller)
public function actionView($id)
{
$model = $this->findModel($id);
$this-> layout = 'surveyformlayout';
$oldpic = $model->member_profile;
if ($model->load(Yii::$app->request->post())) {
$imageName = date("Ymdhis");
$model->file = UploadedFile::getInstance($model,'member_profile');
if(!empty($model->file))
{
$model->file->saveAs('../../backend/web/profile/'.$imageName.'.'.$model->file->extension);
//save the path in the db column
$model->member_profile = 'profile/'.$imageName.'.'.$model->file->extension;
}
else
{
$model->member_profile = $oldpic;
}
$model->updated_at = date("Y-m-d h:i:s");
if($model->save())
{
Yii::$app->session->setFlash('success', 'Add Successful');
return $this->redirect(['view','id'=>$model->id]);
}
else
{
return $this->render('view', [
'model' => $model,
]);
}
}
else{
return $this->render('view', [
'model' => $model,
]);
}
}

It cannot save the cropped image , but can update new image.

Events

Is there a way to respond to events, e.g. do something when an image was uploaded or when it was cropped?

Load the original image in cropbox

You would have to load the original image when you click edit, the cropbox has already been activated. Click on the original image button.

anddusik

namespace app\modules\dusik\models;

use Yii;
use yii\helpers\ArrayHelper;
use yii\helpers\FileHelper;
use yii\imagine\Image;
use yii\helpers\Json;
use Imagine\Image\Box;
use Imagine\Image\Point;
use yii\web\UploadedFile;
/**

  • This is the model class for table "stadium".

  • @Property int $id

  • @Property string|null $name

  • @Property string $id_region

  • @Property string|null $district

  • @Property string|null $address

  • @Property string|null $description

  • @Property string|null $image
    /
    class Stadium extends \yii\db\ActiveRecord
    {
    /
    *

    • {@inheritdoc}
      */
      public static function tableName()
      {
      return 'stadium';
      }

    public $image;
    public $crop_info;

    /**

    • {@inheritdoc}
      */
      public function rules()
      {
      return [
      [['name'], 'string', 'max' => 50],
      [['name'], 'unique', 'message' => 'Такое имя уже используется'],
      [['id_region'], 'required'],
      [['district'], 'string', 'max' => 20],
      [['address', 'description', 'imglogo' ], 'string', 'max' => 255],

       [
       'image', 'image', 'extensions' => ['jpg', 'jpeg', 'png', 'gif'],
       'mimeTypes' => ['image/jpeg', 'image/pjpeg', 'image/png', 'image/gif'],
       ],
       ['crop_info', 'safe'],
      

      ];
      }

    /**

    • {@inheritdoc}
      */
      public function attributeLabels()
      {
      return [
      'id' => 'ID',
      'name' => 'Стадион',
      'id_region' => 'Регион',
      'district' => 'Район',
      'address' => 'Адрес',
      'description' => 'Описание',
      'imglogo' => 'Картинка',
      ];
      }
      public function getRegion(){
      return $this->hasOne(Region::className(), ['id' => 'id_region']);
      }
      public function getCourt(){
      return $this->hasMany(Court::className(), ['id_stadium' => 'id']);
      }
      public static function getList(){
      $list = self::find()->asArray()->all();
      return ArrayHelper::map($list, 'id', 'name');
      }

    public function afterSave($insert, $changedAttributes){

    // open image
    $image = Image::getImagine()->open($this->image->tempName);

    // rendering information about crop of ONE option
    $cropInfo = Json::decode($this->crop_info)[0];
    $cropInfo['dWidth'] = (int)$cropInfo['dWidth']; //new width image
    $cropInfo['dHeight'] = (int)$cropInfo['dHeight']; //new height image
    $cropInfo['x'] = $cropInfo['x']; //begin position of frame crop by X
    $cropInfo['y'] = $cropInfo['y']; //begin position of frame crop by Y
    // Properties bolow we don't use in this example
    //$cropInfo['ratio'] = $cropInfo['ratio'] == 0 ? 1.0 : (float)$cropInfo['ratio']; //ratio image.
    //$cropInfo['width'] = (int)$cropInfo['width']; //width of cropped image
    //$cropInfo['height'] = (int)$cropInfo['height']; //height of cropped image
    //$cropInfo['sWidth'] = (int)$cropInfo['sWidth']; //width of source image
    //$cropInfo['sHeight'] = (int)$cropInfo['sHeight']; //height of source image

    //delete old images
    $oldImages = FileHelper::findFiles(Yii::getAlias('@dusik') . '/web/images/stadium', [
    'only' => [
    $this->id . '.',
    '/thumb_' . $this->id . '.
    ',
    ],
    ]);
    for ($i = 0; $i != count($oldImages); $i++) {
    @Unlink($oldImages[$i]);
    }

    //saving thumbnail
    $newSizeThumb = new Box($cropInfo['dWidth'], $cropInfo['dHeight']);
    $cropSizeThumb = new Box(200, 200); //frame size of crop
    $cropPointThumb = new Point($cropInfo['x'], $cropInfo['y']);
    $pathThumbImage = Yii::getAlias('@dusik') . '/web/images/stadium'
    . '/thumb_'
    . $this->id
    . '.'
    . $this->image->getExtension();

    $image->resize($newSizeThumb)
    ->crop($cropPointThumb, $cropSizeThumb)
    ->save($pathThumbImage, ['quality' => 100]);

    //saving original
    $this->image->saveAs(
    Yii::getAlias('@dusik') . '/web/images/stadium'
    . '/'
    . $this->id
    . '.'
    . $this->image->getExtension()
    );
    }

}

namespace app\modules\dusik\controllers;

use Yii;
use app\modules\dusik\models\Stadium;
use app\modules\dusik\models\StadiumSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use app\modules\dusik\models\Region;
use yii\helpers\ArrayHelper;
use yii\web\UploadedFile;

/**

  • StadiumController implements the CRUD actions for Stadium model.
    /
    class StadiumController extends Controller
    {
    /
    *

    • {@inheritdoc}
      */
      public function behaviors()
      {
      return [
      'verbs' => [
      'class' => VerbFilter::className(),
      'actions' => [
      'delete' => ['POST'],
      ],
      ],
      ];
      }

    /**

    • Lists all Stadium models.

    • @return mixed
      */
      public function actionIndex()
      {
      $searchModel = new StadiumSearch();
      $regions = Region::getList();
      $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

      return $this->render('index', [
      'searchModel' => $searchModel,
      'dataProvider' => $dataProvider,
      'regions' => $regions,
      ]);
      }

    /**

    • Displays a single Stadium model.
    • @param integer $id
    • @return mixed
    • @throws NotFoundHttpException if the model cannot be found
      */
      public function actionView($id)
      {
      return $this->render('view', [
      'model' => $this->findModel($id),
      ]);
      }

    /**

    • Creates a new Stadium model.

    • If creation is successful, the browser will be redirected to the 'view' page.

    • @return mixed
      */
      public function actionCreate()
      {
      $model = new Stadium();
      $regions = Region::getList();

      if ($model->load(Yii::$app->request->post())) {
      // process uploaded image file instance
      $model->image = UploadedFile::getInstance($model, 'image');

       if ($model->save()) {
           // upload only if valid uploaded file instance found
      
           return $this->redirect(['view', 'id'=>$model->id]);
       }
      

      }

      return $this->render('create', [
      'model' => $model,
      'regions' => $regions,
      ]);
      }

    /**

    • Updates an existing Stadium model.

    • If update is successful, the browser will be redirected to the 'view' page.

    • @param integer $id

    • @return mixed

    • @throws NotFoundHttpException if the model cannot be found
      */
      public function actionUpdate($id) {
      $model = $this->findModel($id);
      $regions = Region::getList();

      if ($model->load(Yii::$app->request->post())) {
      // process uploaded image file instance
      $model->image = UploadedFile::getInstance($model, 'image');

       if ($model->save()) {
           // upload only if valid uploaded file instance found
      
           return $this->redirect(['view', 'id'=>$model->id]);
       }
      

      }

      return $this->render('update', [
      'model' => $model,
      'regions' => $regions,
      ]);
      }

    /**

    • Deletes an existing Stadium model.

    • If deletion is successful, the browser will be redirected to the 'index' page.

    • @param integer $id

    • @return mixed

    • @throws NotFoundHttpException if the model cannot be found
      */
      public function actionDelete($id)
      {
      $this->findModel($id)->delete();

      return $this->redirect(['index']);
      }

    /**

    • Finds the Stadium model based on its primary key value.

    • If the model is not found, a 404 HTTP exception will be thrown.

    • @param integer $id

    • @return Stadium the loaded model

    • @throws NotFoundHttpException if the model cannot be found
      */
      protected function findModel($id)
      {
      if (($model = Stadium::findOne($id)) !== null) {
      return $model;
      }

      throw new NotFoundHttpException('The requested page does not exist.');
      }
      }

Undefined index: dHeight

On the afterSave() method I get error saying Undefined index: dHeight..My JQuery version is 2.1.4.
Please Help.

Undefined index (dh/ dHeight/ dheight, x, y)

screen shot 2016-05-23 at 12 47 03 pm

Hi, I'm encountering this problem after I cropped the image and clicked the 'Upload' button to upload it to the server. The 'NULL' on top refers to the result of my "var_dump($this->crop_info);" statement. I have tried changing dHeight to dh, dheight and it didn't work; same goes for x and y. This is how my model looks like:

screen shot 2016-05-23 at 1 50 17 pm

My controller method:

screen shot 2016-05-23 at 1 51 48 pm

My view page code:

screen shot 2016-05-23 at 1 52 34 pm

Trying to get property of non-object

Hi,

Great work,
There is issue when I update my model, there is no option to crop the uploaded image again and If I click on update button I got this error in my Model, at line 74

72 public function afterSave($insert, $changedAttributes) {
73 // open image
74 $image = Image::getImagine()->open($this->icon->tempName);

Update form

Hello,

Is there a way to show the cropped image when we update the record? We are currently saving the cropped image to our server, which is working great, but I also want it that when we update our record, it shows the cropped image.

Bob

Select Wrong Image Type

If you select anything that isn't considered valid i.e. .docx it will still open the crop field and lock everything.

break

It would be nice if there was an edit/recrop button.

I.e A user upload an image and cropped it. They could want to recrop it before saving. You have to reselect the image if you want to crop it again.

It would also be nice to have a remove image / clear button. A user may select an image then want to remove it and not save one.

var control = $("#image-file");
    $(".btnClear").on("click", function() {
        control.replaceWith(control = control.clone(true));
        $("#cropInfo").val('');
        $(".cropped").html('');
    });

gif don't work

affix type as a gif and the photo is not displayed gif

add another button

Hi. I want to add another button next to the Reset Button.
How can I customize the buttons?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.