In this article you will see Codeigniter 4 Resize Image before Upload. Many times we need to Resize Image Before Upload, so we have made a step step guide to resize the image and crop option before uploading and also updated preview options.
So, Let’s begin by creating a simple image cropping and resizing functionality in CodeIgniter 4 projects:
Step 1 – Set Up CodeIgniter 4 app
Start by installing CodeIgniter 4 application with the following command:
composer create-project codeigniter4/appstarter codeigniter4-app
Step 2 – Configure Project
Edit the .env
file in the project root directory 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;
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 upload_form.php
file in the app/views
directory. Include an input field for file selection and setup for image cropping and resizing:
<!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>
<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>
</body>
</html>
Step 5 – Implement Cropper Js Code
In the upload_form.php
view file, integrate Cropper js code to enable image cropping, resizing, and upload to the 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
Add routes in the 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 the application server:
php spark serve
This completes the step-by-step guide to implementing image cropping and resizing functionality using Cropper js in CodeIgniter 4, enhancing your application’s image upload capabilities.