PHP code example of dpodium / yii2-widget-upload-crop

1. Go to this page and download the library: Download dpodium/yii2-widget-upload-crop 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/ */

    

dpodium / yii2-widget-upload-crop example snippets


...
	use yii\base\DynamicModel;
	use yii\web\UploadedFile;
	use yii\imagine\Image;
	use Imagine\Image\Box;
...
	$uploadParam = 'avatar';
	$maxSize = 2097152;
	$extensions = 'jpeg, jpg, png, gif';
	$width = 200;
	$height = 200;
	if (Yii::$app->request->isPost) {
		$model = new DynamicModel([$uploadParam]);
		$model->load(Yii::$app->request->post());
		$model->{$uploadParam} = UploadedFile::getInstance($model, $uploadParam);
		$model->addRule($uploadParam, 'image', [
			'maxSize' => $maxSize,
			'extensions' => explode(', ', $extensions),
		])->validate();

		if ($model->hasErrors()) {
			Yii::$app->session->setFlash("warning", $model->getFirstError($uploadParam));
		} else {
			$name = Yii::$app->user->id . '.png';
			$cropInfo = Yii::$app->request->post('cropping');

			try {
				$image = Image::crop(
					$model->{$uploadParam}->tempName,
					intval($cropInfo['width']),
					intval($cropInfo['height']),
					[$cropInfo['x'], $cropInfo['y']]
				)->resize(
					new Box($width, $height)
				);
			} catch (\Exception $e) {
				Yii::$app->session->setFlash("warning", $e->getMessage());
			}

			//upload and save db
			$path = 'images/'.$name;
			if (isset($image) && $image->save($path)) {
				...
				//store your image info to db here
				...
				Yii::$app->session->setFlash("success", Yii::t('alert', 'Avatar upload success.'));
			} else {
				Yii::$app->session->setFlash("warning", Yii::t('alert', 'Avatar upload failed.'));
			}
		}
		return $this->redirect(['account/index']);
	} else {
		throw new BadRequestHttpException(Yii::t('cropper', 'ONLY_POST_REQUEST'));
	}

php composer.phar