Date Posted:02-06-2017

In this post We will explain image upload with crop,resize in codeigniter using jquery plugin
I assume that you are  configure or setup the codeigniter

step 1:
Download the jquery.min.js and jquery.Jcrop.min.js,Jcrop.css files and link to script or use cdn link.

<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 new js file inside assets folder and give name script.js and 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: CI app’s application/views folder and lets create a view file named crop_view.php. and add the script following script code

            $(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: After  crop_view.php inside div add following code and also link the script.js(Refer step2)

  <?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: Navigate to your controllers folder and create a file named crop.php and add the following code to it

<?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();
           
      } 
         } 
 
  }
}

 

3 thoughts on “CodeIgniter Image Upload and Crop,resize”

  1. 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.

    1. 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?

Leave a Reply