sabirov / yii2-bootstrap4-cropper
为 Yii2 的 Cropper
0.1.4
2021-01-09 11:34 UTC
Requires
- php: >=5.4.0
- fxp/composer-asset-plugin: ^1.4.4
- npm-asset/cropperjs: ^1.4.3
- yiisoft/yii2: ~2.0.6
- yiisoft/yii2-bootstrap4: ~1.0.0
This package is not auto-updated.
Last update: 2024-09-29 06:25:40 UTC
README
使用 Bootstrap4 的 Yii2 的 Cropper
包装 cropperjs。
安装
通过 composer 安装此扩展是首选方式。
运行以下命令之一
php composer.phar require sabirov/yii2-bootstrap4-cropper
或者
"sabirov/yii2-bootstrap4-cropper": "^0.1.1"
将以下内容添加到您的 composer.json
文件的 require 部分中。
使用方法
在您的模型中,您需要添加以下代码
public $_avatar; // variable to get the picture public function rules() { return [ ['_avatar', 'safe'], // must be set to "safe" ]; } public function beforeSave($insert) { if (is_string($this->_avatar) && strstr($this->_avatar, 'data:image')) { $uploadPath = Yii::getAlias('@web') . '/upload'; // set a directory to save picture $data = $this->_avatar; $data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $data)); $fileName = Yii::$app->security->generateRandomString() . '.png'; // generate picture name file_put_contents($uploadPath . DIRECTORY_SEPARATOR . $fileName, $data); if (!empty($this->avatar)) { // "avatar" model attribute which stores picture name unlink(Yii::getAlias($uploadPath . DIRECTORY_SEPARATOR . $this->avatar)); // delete old picture } $this->avatar = $fileName; // set new picture name to attribute } return parent::beforeSave($insert); }
视图文件中的简单使用
use sabirov\cropper\Cropper; $uploadPath = Yii::getAlias('@web') . '/upload'; $img_url = is_null($model->avatar) ? null : $uploadPath . DIRECTORY_SEPARATOR . $model->avatar; $form = ActiveForm::begin(); echo $form->field($model, '_avatar')->widget(Cropper::class, [ 'previewImageUrl' => $img_url, // if 'null' set url to no-image.svg ]); echo Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']); ActiveForm::end();
视图文件中的高级使用
use sabirov\cropper\Cropper; $uploadPath = Yii::getAlias('@web') . '/upload'; $img_url = is_null($model->avatar) ? null : $uploadPath . DIRECTORY_SEPARATOR . $model->avatar; $form = ActiveForm::begin(); echo $form->field($model, '_avatar')->widget(Cropper::class, [ 'previewImageUrl' => $img_url, // if 'null' set url to no-image.svg 'extensionOptions' => [ 'preview' => [ 'width' => 270, 'height' => 270 ], 'browseButtonText' => 'Выбрать', 'cropButtonText' => 'Обрезать', 'changeButtonText' => 'Изменить', 'closeButtonText' => 'Закрыть', 'cropperWarningText' => 'Двойной клик - переключение между перемещением изображения и выбором области обрезки.' ], 'cropperOptions' => [ 'viewMode' => 1, 'aspectRatio' => 1, 'minContainerHeight' => 270, 'minCropBoxHeight' => 270 ] ]); echo Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']); ActiveForm::end();
extensionOptions 属性
cropperOptions 请参阅 cropperjs 选项。