jQuery Croppie js is a lightweight javascript library that allows users to crop and resize image on form views before uploading to server.
Codeigniter 4 Crop & Save Image using jQuery Croppie Example Tutorial
Here are steps to crop, resize images before upload to server using jquery croppie js with ajax in PHP:
- Step 1: Download Codeigniter Project
- Step 2: Basic Configurations
- Step 3: Create a Database With Table
- Step 4: Setup Database Credentials
- Step 5: Create a Controller
- Step 6: Create a View
- Step 7: Start the Development server
Step 1: Download Codeigniter Project
In this step, we will download the latest version of Codeigniter 4, Go to this link https://codeigniter.com/download Download Codeigniter 4 fresh new setup and unzip the setup in your local system xampp/htdocs/ . And change the download folder name “demo”
Step 2: Basic Configurations
Open app/config/app.php file, and add the following line into it:
Set Base URL like this
public $baseURL = 'http://localhost:8080'; To public $baseURL = 'http://localhost/demo/';
Step 3: Create a Database With Table
To create table in the database, use the below SQL query for that:
CREATE TABLE crop_images (
id int(11) NOT NULL AUTO_INCREMENT COMMENT 'Primary Key',
title varchar(100) NOT NULL COMMENT 'Title',
created_at varchar(20) NOT NULL COMMENT 'Created date',
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='demo table' AUTO_INCREMENT=1;
Step 4: Setup Database Credentials
Open app/Config/Database.php and setup database details like the following:
public $default = [
'DSN' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'demo',
'DBDriver' => 'MySQLi',
'DBPrefix' => '',
'pConnect' => false,
'DBDebug' => (ENVIRONMENT !== 'production'),
'cacheOn' => false,
'cacheDir' => '',
'charset' => 'utf8',
'DBCollat' => 'utf8_general_ci',
'swapPre' => '',
'encrypt' => false,
'compress' => false,
'strictOn' => false,
'failover' => [],
'port' => 3306,
];
Step 5: Create a Controller
Visit app/Controllers folder and create a controller name CropImageUpload.php file into it. And then create some methods into it to display crop images before uploading form and validate the image before uplaod.
<?php namespace App\Controllers;
use CodeIgniter\Controller;
class CropImageUpload extends Controller
{
public function index()
{
return view('crop-image-upload-form');
}
public function store()
{
helper(['form', 'url']);
$db = \Config\Database::connect();
$builder = $db->table('crop_images');
$data = $_POST["image"];
$image_array_1 = explode(";", $data);
$image_array_2 = explode(",", $image_array_1[1]);
$data = base64_decode($image_array_2[1]);
$imageName = time() . '.png';
file_put_contents($imageName, $data);
$image_file = addslashes(file_get_contents($imageName));
$save = $builder->insert(['title' => $image_file]);
$response = [
'success' => true,
'data' => $save,
'msg' => "Crop Image has been uploaded successfully in codeigniter"
];
return $this->response->setJSON($response);
}
}
Step 6: Create a View
Create crop-image-upload-form.php file in application/views/ folder and add the following code into it:
<html>
<head>
<title>jQuery Croppie Image Upload Crop Codeigniter 4</title>
</head>
<body>
<div class="container mt-5">
<div class="card">
<div class="card-header">
jQuery Crop and Resize Image Before Upload in PHP Codeigniter 4
</div>
<div class="card-body">
<input type="file" name="before_crop_image" id="before_crop_image" accept="image/*" />
</div>
</div>
</div>
</body>
</html>
<div id="imageModel" class="modal fade bd-example-modal-lg" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Crop & Resize Upload Image in PHP with Ajax</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-8 text-center">
<div id="image_demo" style="width:350px; margin-top:30px"></div>
</div>
<div class="col-md-4" style="padding-top:30px;">
<br />
<br />
<br/>
<button class="btn btn-success crop_image">Save</button>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</script>
Add the following jQuery croppie plugin libaray in crop-image-upload-form.php file:
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script
>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/croppie/2.6.5/croppie.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/croppie/2.6.5/croppie.css" />
Then, add this below code into crop-image-upload-form.php file to crop image before upload on boostrap model in codeigniter:
$image_crop = $('#image_demo').croppie({
enableExif: true,
viewport: {
width:200,
height:200,
type:'square' //circle
},
boundary:{
width:300,
height:300
}
});
$('#before_crop_image').on('change', function(){
var reader = new FileReader();
reader.onload = function (event) {
$image_crop.croppie('bind', {
url: event.target.result
}).then(function(){
console.log('jQuery bind complete');
});
}
reader.readAsDataURL(this.files[0]);
$('#imageModel').modal('show');
});
Also, add this below ajax code in crop-image-upload-form.php for upload crop image into controller file in codeigniter 4 projects:
$('.crop_image').click(function(event){
$image_crop.croppie('result', {
type: 'canvas',
size: 'viewport'
}).then(function(response){
$.ajax({
url:"<?php echo base_url(); ?>public/index.php/CropImageUpload/store",
type:'POST',
data:{"image":response},
success:function(data){
$('#imageModel').modal('hide');
alert('Crop image has been uploaded');
}
})
});
});
Step 7: Start Development server
To start the development server, Go to the browser and hit below the URL.
http://localhost/demo/public/index.php/crop-image-upload
Conclusion
That’s all; In this tutorial, You have learned how to crop and resize image before upload in CodeIgniter 4 projects using jQuery croppie with ajax with preview.
Recommended Codeigniter Posts
If you have any questions or thoughts to share, use the comment form below to reach us.