PHP code example of dmbozhok / yii2-bootstrap4-cropper
1. Go to this page and download the library: Download dmbozhok/yii2-bootstrap4-cropper 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/ */
dmbozhok / yii2-bootstrap4-cropper example snippets
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);
}