Cropper js allow developers to implement feature in application to crop and resize images before upload to server.
Let’s start creating a simple crop and resize image before upload in codeIgniter 4 projects:
Step 1 – Set Up CodeIgniter 4 Project
Run the following command to install codeIgniter 4 application:
composer create-project codeigniter4/appstarter codeigniter4-demo
Step 2 – Configure Project
Edit the .env
file from root directory of project and set the app.baseURL
:
app.baseURL = 'http://localhost:8080'
Step 3 – Create the Controller
Create controller file named ImageUploadController.php
in app/controllers
directory, and implement methods in it to handle multiple file upload via ajax:
<?php
namespace App\Controllers;
use CodeIgniter\Controller;
use CodeIgniter\HTTP\ResponseInterface;
class ImageUploadController extends Controller
{
public function index()
{
return view('upload_form');
}
public function uploadCroppedImage()
{
$img = $this->request->getPost('croppedImage');
list($type, $img) = explode(';', $img);
list(, $img) = explode(',', $img);
$img = base64_decode($img);
$fileName = uniqid() . '.png';
file_put_contents(WRITEPATH . 'uploads/' . $fileName, $img);
return $this->response->setJSON([
'status' => 'success',
'file' => $fileName
]);
}
}
Step 4 – Create Image Upload View
Create the upload_form.php
file in the app/views
directory, and add the input file upload so users can select the file to cut, resize, and upload:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Upload and Crop Image</title>
<!-- Bootstrap CSS -->
<link href="https://stackpath.bootstrapcdn.com/bootstrap/5.1.3/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.12/cropper.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.12/cropper.min.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<div class="container mt-5">
<h2 class="mb-4">Upload and Crop Image</h2>
<div class="mb-3">
<input type="file" class="form-control" id="imageInput">
</div>
<div class="mb-3">
<img id="image" class="img-fluid" style="display: none;">
</div>
<button id="cropButton" class="btn btn-primary">Crop and Upload</button>
<div id="uploadStatus" class="mt-3"></div>
</div>
<!-- Bootstrap JS and Popper.js -->
<script src="https://stackpath.bootstrapcdn.com/bootstrap/5.1.3/js/bootstrap.bundle.min.js"></script>
</body>
</html>
Step 5 – Implement Cropper Js Code
Edit form form_upload.php
view file, and implement cropper js code in it to crop, resize and upload image to server:
<script>
let cropper;
const image = document.getElementById('image');
$('#imageInput').on('change', function (e) {
const files = e.target.files;
const done = (url) => {
image.src = url;
$('#image').show();
cropper = new Cropper(image, {
aspectRatio: 1,
viewMode: 3,
preview: '.preview'
});
};
if (files && files.length > 0) {
const reader = new FileReader();
reader.onload = () => done(reader.result);
reader.readAsDataURL(files[0]);
}
});
$('#cropButton').on('click', function () {
const canvas = cropper.getCroppedCanvas({
width: 300,
height: 300
});
canvas.toBlob(function (blob) {
const url = URL.createObjectURL(blob);
const reader = new FileReader();
reader.readAsDataURL(blob);
reader.onloadend = function () {
const base64data = reader.result;
$.ajax({
url: '<?= base_url('upload-cropped-image') ?>',
method: 'POST',
data: {croppedImage: base64data},
success: function (response) {
if (response.status === 'success') {
$('#uploadStatus').html('<div class="alert alert-success">Image uploaded successfully!<br>File name: ' + response.file + '</div>');
} else {
$('#uploadStatus').html('<div class="alert alert-danger">Some problem occurred, please try again.</div>');
}
}
});
};
});
});
</script>
Step 6 – Define Routes
Define the routes in app/Config/Routes.php
file to handle crop image upload requests:
$routes->get('/', 'ImageUploadController::index');
$routes->post('upload-cropped-image', 'ImageUploadController::uploadCroppedImage');
Step 7 – Test the Application
Run the following command to start application server:
php spark serve
Type http://localhost:8080
url on browser to test this application.