Yii2 Image Cropper
, (*1)
A simple wrapper for the imgAreaSelect jquery plugin, (*2)
Installation
The preferred way to install this extension is through composer., (*3)
Either run, (*4)
php composer.phar require --prefer-dist cozumel/yii2-image-cropper "*"
or add, (*5)
"cozumel/yii2-image-cropper": "*"
to the require section of your composer.json
file., (*6)
Usage
Once the extension is installed, simply use it in your code by :, (*7)
<?= \cozumel\cropper\ImageCropper::widget(); ?>
Example
View File:, (*8)
<?= \cozumel\cropper\ImageCropper::widget(['id' => 'user_profile_photo']); ?>
Where user_profile_photo
is the id of the image to use., (*9)
Html in view file:, (*10)
The main image you will be cropping:, (*11)
<img width="<?= $width; ?>" height="<?= $height; ?>" max-width="<?=$max_width;?>" class="border" id="user_profile_photo" alt="<?=alt_text;?>" src="<?= image_source; ?>">
The preview image:
(the ids here are fixed, and the 75px must be stated but can be changed), (*12)
The form to send the information to your controller:, (*13)
Yii::$app->urlManager->createUrl(['your/url/here']), 'options' => ['id' => 'crop_form'],
]);
?>
Javascript to submit the form:, (*14)
$(document).ready(function () {
$(document.body).on('submit', '#crop_form', function (e) {
var frm = $(this); //just sent text
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
dataType: 'json',
data: frm.serialize(),
success: function (data) {
if (data) {
//do something
}
},
});
return false;
});
});
Your controller function:
```php
$request = Yii::$app->request;, (*15)
$x1 = $request->post('x1');
$x2 = $request->post('x2');
$y1 = $request->post('y1');
$y2 = $request->post('y2');, (*16)
$h = $request->post('h');
$w = $request->post('w');, (*17)
$image_height = $request->post('image_height');
$image_width = $request->post('image_width');, (*18)
if (empty($w)) {
//nothing selected
return;
}
$image = imagecreatefromjpeg($image_source);, (*19)
$width = imagesx($image);
$height = imagesy($image);, (*20)
$resized_width = ((int) $x2) - ((int) $x1);
$resized_height = ((int) $y2) - ((int) $y1);, (*21)
$resized_image = imagecreatetruecolor($resized_width, $resized_height);
imagecopyresampled($resized_image, $image, 0, 0, (int) $x1, (int) $y1, $width, $height, $width, $height);
imagejpeg($resized_image, $image_source);
```, (*22)