Introduction
Image upload and image editing are common requirements in web applications. CodeIgniter provides built-in libraries for handling file uploads and image manipulation, while jQuery plugins can be used to provide an interactive image cropping interface.
In this guide, we will explain how to implement image upload and cropping in CodeIgniter using the Jcrop jQuery plugin and CodeIgniter’s upload and image manipulation libraries.
The implementation allows users to select an image, choose a crop region, and upload the cropped image.
Prerequisites
Before starting, make sure:
- CodeIgniter is installed and configured.
- PHP and a web server are available.
- jQuery and Jcrop libraries are available.
- The application has write permission for the
assetsdirectory. - Basic knowledge of CodeIgniter, PHP, HTML, JavaScript, and jQuery is recommended.
Implementation
Step 1: Include jQuery and Jcrop
Download the following files and link them to your application, or use the CDN links:
jquery.min.jsjquery.Jcrop.min.jsJcrop.css
<source type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></source> <link rel="stylesheet" href="http://jcrop-cdn.tapmodo.com/v0.9.12/css/jquery.Jcrop.css" type="text/css" /> <source type="text/javascript" src="http://jcrop-cdn.tapmodo.com/v0.9.12/js/jquery.Jcrop.js"></source>
Step 2: Create script.js
Create a new JavaScript file inside the assets folder with the name:
script.js
Add the following code:
// convert bytes into friendly format
function bytesToSize(bytes) {
var sizes = ['Bytes', 'KB', 'MB'];
if (bytes == 0) return 'n/a';
var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
return (bytes / Math.pow(1024, i)).toFixed(1) + ' ' + sizes[i];
};
// check for selected crop region
function checkForm() {
if (parseInt($('#w').val())) return true;
$('.error').html('Please select a crop region and then press Upload').show();
return false;
};
// update info by cropping (onChange and onSelect events handler)
function updateInfo(e) {
$('#x1').val(e.x);
$('#y1').val(e.y);
$('#x2').val(e.x2);
$('#y2').val(e.y2);
$('#w').val(e.w);
$('#h').val(e.h);
};
// clear info by cropping (onRelease event handler)
function clearInfo() {
$('.info #w').val('');
$('.info #h').val('');
};
// Create variables (in this scope) to hold the Jcrop API and image size
var jcrop_api, boundx, boundy;
function fileSelectHandler() {
// get selected file
var oFile = $('#image_file')[0].files[0];
// hide all errors
$('.error').hide();
// check for image type (jpg and png are allowed)
var rFilter = /^(image\/jpeg|image\/png)$/i;
if (! rFilter.test(oFile.type)) {
$('.error').html('Please select a valid image file (jpg and png are allowed)').show();
return;
}
// check for file size
if (oFile.size > 250 * 1024) {
$('.error').html('You have selected too big file, please select a one smaller image file').show();
return;
}
if (oFile.size < 300 * 300) {
$('.error').html('You have selected too small file, please select a one bigger image file').show();
return;
}
// preview element
var oImage = document.getElementById('preview');
// prepare HTML5 FileReader
var oReader = new FileReader();
oReader.onload = function(e) {
// e.target.result contains the DataURL which we can use as a source of the image
oImage.src = e.target.result;
oImage.onload = function () { // onload event handler
// display step 2
$('.step2').fadeIn(500);
// display some basic image info
var sResultFileSize = bytesToSize(oFile.size);
$('#filesize').val(sResultFileSize);
$('#filetype').val(oFile.type);
$('#filedim').val(oImage.naturalWidth + ' x ' + oImage.naturalHeight);
// destroy Jcrop if it is existed
if (typeof jcrop_api != 'undefined') {
jcrop_api.destroy();
jcrop_api = null;
$('#preview').width(oImage.naturalWidth);
$('#preview').height(oImage.naturalHeight);
}
setTimeout(function(){
// initialize Jcrop
$('#preview').Jcrop({
minSize: [32, 32], // min crop size
aspectRatio : 1, // keep aspect ratio 1:1
bgFade: true, // use fade effect
bgOpacity: .3, // fade opacity
onChange: updateInfo,
onSelect: updateInfo,
onRelease: clearInfo
}, function(){
// use the Jcrop API to get the real image size
var bounds = this.getBounds();
boundx = bounds[0];
boundy = bounds[1];
// Store the Jcrop API in the jcrop_api variable
jcrop_api = this;
});
},3000);
};
};
// read selected file as DataURL
oReader.readAsDataURL(oFile);
}
Step 3: Create the Crop View
Inside the CodeIgniter application/views folder, create a view file named:
crop_view.php
Add the following script:
$(function(){
$('#cropbox').Jcrop({
aspectRatio: 1,
onSelect: updateCoords
});
});
function updateCoords(c)
{
$('#x').val(c.x);
$('#y').val(c.y);
$('#w').val(c.w);
$('#h').val(c.h);
};
function checkCoords()
{
if (parseInt($('#w').val())) return true;
alert('Select where you want to Crop.');
return false;
};
Step 4: Add the Image Upload and Crop Form
Inside crop_view.php, add the following code and link script.js created in Step 2.
<?php $this->load->helper('url');
<!DOCTYPE html>
<html>
<head>
<title>Crop Image</title>
<source type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></source>
<link rel="stylesheet" href="http://jcrop-cdn.tapmodo.com/v0.9.12/css/jquery.Jcrop.css" type="text/css" />
<source type="text/javascript" src="http://jcrop-cdn.tapmodo.com/v0.9.12/js/jquery.Jcrop.js"></source>
<source type="text/javascript" src="<?=base_url().'assets/script.js'?>"></source>
</head>
<body>
<form action="site_url('crop/cropImg)?> method="post" onSubmit="return checkForm()" entype="multipart/form-data">
<input type="hidden" id="x1" name="x1" />
<input type="hidden" id="y1" name="y1" />
<input type="hidden" id="x2" name="x2" />
<input type="hidden" id="y2" name="y2" />
<input type="file" name="image_file" class="loginlink image_class" id="image_file" onChange="fileSelectHandler()"/>
<img id="preview" />
<label class="info1">File size</label> <input type="text" class="info1" id="filesize" name="filesize" />
<label class="info1">Type</label> <input type="text" class="info1" id="filetype" name="filetype" />
<label class="info1">Image dimension</label> <input type="text" class="info1" id="filedim" name="filedim" />
<label class="info1">W</label> <input type="text" class="info1" id="w" name="w" />
<label class="info1">H</label> <input type="text" class="info1" id="h" name="h" />
<input type="submit" class="img-upload" value="Upload"/>
</form>
<body>
Step 5: Create the Controller
Navigate to:
application/controllers
Create a file named:
crop.php
Add the following code:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Crop extends CI_Controller {
/**
* Index Page for this controller.
*
* Maps to the following URL
* http://example.com/index.php/welcome
* - or -
* http://example.com/index.php/welcome/index
* - or -
* Since this controller is set as the default controller in
* config/routes.php, it's displayed at http://example.com/
*
* So any other public methods not prefixed with an underscore will
* map to /index.php/welcome/<method_name>
* @see https://codeigniter.com/user_guide/general/urls.html
*/
public function index()
{
$this->load->view('crop_view');
}
public function cropImg()
{
if ($_FILES)
{
$config['upload_path'] = './assets/';
$config['allowed_types'] = '*';
$config['encrypt_name']= true;
$this->load->library('upload', $config);
if (!is_dir($config['upload_path'])) {
mkdir($config['upload_path'], 0777, TRUE);
}
if ( ! $this->upload->do_upload('image_file')) {
$error = array('error' => $this->upload->display_errors());
}
else
{
// $width=200;
// $height=200;
$up_file_data = $this->upload->data();
$config['image_library'] = 'gd2';
$config['source_image'] = $config['upload_path'].'/'.$up_file_data['file_name'];
$config['x_axis'] = $this->input->post('x1');
$config['y_axis'] = $this->input->post('y1');
$config['maintain_ratio'] = FALSE;
$config['width'] = $this->input->post('w');
$config['height'] = $this->input->post('h');
$config['quality'] = '90%';
$this->load->library('image_lib', $config);
$this->image_lib->crop();
}
}
}
}
The controller performs the upload and uses CodeIgniter’s image library to crop the uploaded image according to the coordinates submitted by the form.
Conclusion
CodeIgniter can be used together with the Jcrop jQuery plugin to provide an interactive image upload and crop feature. The client-side JavaScript handles image selection and crop coordinates, while the CodeIgniter controller processes the uploaded image and performs the crop operation.
This approach can be useful for profile images, product images, thumbnails, and other applications where users need to select a specific portion of an uploaded image.
FAQs
1. What is Jcrop used for?
Jcrop is used to provide an interactive image cropping interface where users can select the portion of an image they want to crop.
2. Which CodeIgniter library is used for image cropping?
The implementation uses CodeIgniter’s image_lib library with the gd2 image library.
3. Where is the uploaded image stored?
The uploaded image is stored in the ./assets/ directory configured in the controller.
4. What image formats are accepted in this implementation?
The JavaScript validation allows JPEG and PNG images.
5. Can the crop size be controlled?
Yes. The Jcrop configuration uses:
minSize: [32, 32]
and:
aspectRatio : 1
This creates a minimum crop size and keeps the crop area square.
Related Articles
Send Email Using HTML Templates in CodeIgniter
Learn how to send emails using HTML templates in a CodeIgniter application.
https://pheonixsolutions.com/blog/send-email-using-html-templates-codeigniter/
Currency Conversion and Symbol Library in CodeIgniter
Learn how to implement currency conversion and work with currency symbols in CodeIgniter applications.
https://pheonixsolutions.com/blog/currency-conversion-and-symbol-library-in-codeigniter
Talk to our experts
Looking for the right technology solution for your business? Our team of experts can help you with development, cloud, DevOps, design, and a wide range of other technology needs. Get in touch with our team here.
Hello, it seems some portions of your code are missing in step 1 after “if (oFile.size” could you please post an archive of the project in order to get the full code please? Thnks.
We have updated the code and verified it from our end. Could you please try the latest one and incase if you face any issue, please update here?
I am not able to upload cropped image, it will upload original image