使用Codeigniter的Croppic jQuery插件

As I was looking for a crop plugin that works with codeigniter, I came across this example: Working Demo

So I've downloaded the source files, got it working until I tried to connect it to the database. I've followed the instructions from the site and here are the codes from the file.

Model:

function store_logo($file)
{
$insert = $this->db->update('logo', $file);
return $insert;
}

View:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta name="description" content="">
        <meta name="author" content="">
        <link rel="shortcut icon" href="<?php echo base_url() . 'assets/img/favicon.png' ?>">

        <title>croppic image cropping pluggin for code igniter</title>

        <!-- Bootstrap core CSS -->
        <link href="<?php echo base_url() . 'assets/css/bootstrap.css" rel="stylesheet' ?>">

        <!-- Custom styles for this template -->
        <link href="<?php echo base_url() . 'assets/css/main.css" rel="stylesheet' ?>">
        <link href="<?php echo base_url() . 'assets/css/croppic.css" rel="stylesheet' ?>">

        <!-- Fonts from Google Fonts -->
        <link href='http://fonts.googleapis.com/css?family=Lato:300,400,900' rel='stylesheet' type='text/css'>
        <link href='http://fonts.googleapis.com/css?family=Mrs+Sheppards&subset=latin,latin-ext' rel='stylesheet' type='text/css'>



        <!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
        <!--[if lt IE 9]>
          <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
          <script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script>
        <![endif]-->

    </head>

    <body>

<h1 align="center">Cropic Image Cropping Pluggin for Codeigniter  </h1>



        <div class="container">
            <div class="row mt"><div style="float:left">
</div>
<style>.myButton {
    -moz-box-shadow: 0px 10px 22px -7px #3e7327;
    -webkit-box-shadow: 0px 10px 22px -7px #3e7327;
    box-shadow: 0px 10px 22px -7px #3e7327;
    background:-webkit-gradient(linear, left top, left bottom, color-stop(0.05, #77b55a), color-stop(1, #72b352));
    background:-moz-linear-gradient(top, #77b55a 5%, #72b352 100%);
    background:-webkit-linear-gradient(top, #77b55a 5%, #72b352 100%);
    background:-o-linear-gradient(top, #77b55a 5%, #72b352 100%);
    background:-ms-linear-gradient(top, #77b55a 5%, #72b352 100%);
    background:linear-gradient(to bottom, #77b55a 5%, #72b352 100%);
    filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#77b55a', endColorstr='#72b352',GradientType=0);
    background-color:#77b55a;
    -moz-border-radius:2px;
    -webkit-border-radius:2px;
    border-radius:2px;
    border:1px solid #4b8f29;
    display:inline-block;
    cursor:pointer;
    color:#ffffff;
    font-family:Arial;
    font-size:28px;
    font-weight:bold;
    padding:8px 76px;
    text-decoration:none;
    text-shadow:0px 1px 0px #5b8a3c;
}
.myButton:hover {
    background:-webkit-gradient(linear, left top, left bottom, color-stop(0.05, #72b352), color-stop(1, #77b55a));
    background:-moz-linear-gradient(top, #72b352 5%, #77b55a 100%);
    background:-webkit-linear-gradient(top, #72b352 5%, #77b55a 100%);
    background:-o-linear-gradient(top, #72b352 5%, #77b55a 100%);
    background:-ms-linear-gradient(top, #72b352 5%, #77b55a 100%);
    background:linear-gradient(to bottom, #72b352 5%, #77b55a 100%);
    filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#72b352', endColorstr='#77b55a',GradientType=0);
    background-color:#72b352;
}
.myButton:active {
    position:relative;
    top:1px;
}
</style>


<div style="clear:both"></div>
<div class="row mt ">


  <div class="col-lg-4 ">
    <h4 class="centered" style="color:#CC0000">DEMO/ OUTPUT </h4>
    <p class="centered">( display url after cropping )</p>
    <div id="cropContaineroutput"></div>
    <input type="text" id="cropOutput" style="width:100%; padding:5px 4%; margin:20px auto; display:block; border: 1px solid #CCC;" />
  </div>
  <div class="col-lg-8 ">
    <h2>To Store the image in mydql Database, Folow the below code</h2>
    <strong>Step1: Create databse</strong>
    <p><code>CREATE TABLE IF NOT EXISTS `logo` (
      `id` int(11) NOT NULL,
      `photo` varchar(255) COLLATE utf8_unicode_ci NOT NULL
      ) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;</code></p>
    </div>
    <strong>Step2: In controller home.php</strong><br>
    <code>  imagejpeg($final_image, $output_filename.$type, $jpeg_quality);<br>
     $response = Array(<br>
     "status" => 'success',<br>
     "url" => base_url(). $output_filename.$type
     );<br>
     $output=str_replace('temp/', '', $output_filename);<br>
     $file=array(<br>
     'photo'=>$output,<br>
     );<br>
     $this->Logo_model->store_logo($file);</code><br>
     <strong>Step3: In model Logo_model.php</strong><br>
     <code>   function store_logo($file)<br>
      {<br>

      $insert = $this->db->update('logo', $file);<br>
      return $insert;<br>
    }</code>

  </div>


</div>


<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<!-- <script src="https://code.jquery.com/jquery-1.10.2.min.js"></script> -->
<script src=" https://code.jquery.com/jquery-2.1.3.min.js"></script>

<script src="<?php echo base_url() . 'assets/js/bootstrap.min.js' ?>"></script>
<script src="<?php echo base_url() . 'assets/js/jquery.mousewheel.min.js' ?>"></script>
<script src="<?php echo base_url() . 'assets/js/croppic.min.js' ?>"></script>
<script src="<?php echo base_url() . 'assets/js/main.js' ?>"></script>
  <script>

  var croppicContaineroutputOptions = {
     uploadUrl: '<?php echo base_url() . "home/img_save_to_file" ?>',
     cropUrl: '<?php echo base_url() . "home/img_crop_to_file" ?>',
     outputUrlId: 'cropOutput',
     modal: false,
     loaderHtml: '<div class="loader bubblingG"><span id="bubblingG_1"></span><span id="bubblingG_2"></span><span id="bubblingG_3"></span></div> ',
     onBeforeImgUpload: function () { console.log('onBeforeImgUpload')},
     onAfterImgUpload: function () {console.log('onAfterImgUpload')},
     onImgDrag: function () {console.log('onImgDrag')},
     onImgZoom: function () {console.log('onImgZoom')},
     onBeforeImgCrop: function () {console.log('onBeforeImgCrop')},
     onAfterImgCrop: function () {console.log('onAfterImgCrop')},
     onReset: function () {console.log('onReset')},
     onError: function (errormessage) {console.log('onError:' + errormessage)}
  }

  var cropContaineroutput = new Croppic('cropContaineroutput', croppicContaineroutputOptions);

  </script>

  </body>
</html>

Controller:

class Home extends CI_Controller {

public function index()
{
    $this->load->view('imagem');
}

public function img_crop_to_file() {

    $imgUrl = $_POST['imgUrl'];
// original sizes
        $imgInitW = $_POST['imgInitW'];
        $imgInitH = $_POST['imgInitH'];
// resized sizes
        $imgW = $_POST['imgW'];
        $imgH = $_POST['imgH'];
// offsets
        $imgY1 = $_POST['imgY1'];
        $imgX1 = $_POST['imgX1'];
// crop box
        $cropW = $_POST['cropW'];
        $cropH = $_POST['cropH'];
// rotation angle
        $angle = $_POST['rotation'];

    $jpeg_quality = 100;

    $output_filename = "temp/croppedImg_".rand();

// uncomment line below to save the cropped image in the same location as the original image. // $output_filename = dirname($imgUrl). "/croppedImg_".rand();

    $what = getimagesize($imgUrl);

    switch(strtolower($what['mime']))
    {
        case 'image/png':
        $img_r = imagecreatefrompng($imgUrl);
        $source_image = imagecreatefrompng($imgUrl);
        $type = '.png';
        break;
        case 'image/jpeg':
        $img_r = imagecreatefromjpeg($imgUrl);
        $source_image = imagecreatefromjpeg($imgUrl);
        error_log("jpg");
        $type = '.jpeg';
        break;
        case 'image/gif':
        $img_r = imagecreatefromgif($imgUrl);
        $source_image = imagecreatefromgif($imgUrl);
        $type = '.gif';
        break;
        default: die('image type not supported');
    }

//Check write Access to Directory

    if(!is_writable(dirname($output_filename))){
        $response = Array(
            "status" => 'error',
            "message" => 'Can`t write cropped File'
            );  
    }else{

// resize the original image to size of editor
        $resizedImage = imagecreatetruecolor($imgW, $imgH);
        imagecopyresampled($resizedImage, $source_image, 0, 0, 0, 0, $imgW, $imgH, $imgInitW, $imgInitH);
// rotate the rezized image
        $rotated_image = imagerotate($resizedImage, -$angle, 0);
// find new width & height of rotated image
        $rotated_width = imagesx($rotated_image);
        $rotated_height = imagesy($rotated_image);
// diff between rotated & original sizes
        $dx = $rotated_width - $imgW;
        $dy = $rotated_height - $imgH;
// crop rotated image to fit into original rezized rectangle
        $cropped_rotated_image = imagecreatetruecolor($imgW, $imgH);
        imagecolortransparent($cropped_rotated_image, imagecolorallocate($cropped_rotated_image, 0, 0, 0));
        imagecopyresampled($cropped_rotated_image, $rotated_image, 0, 0, $dx / 2, $dy / 2, $imgW, $imgH, $imgW, $imgH);
// crop image into selected area
        $final_image = imagecreatetruecolor($cropW, $cropH);
        imagecolortransparent($final_image, imagecolorallocate($final_image, 0, 0, 0));
        imagecopyresampled($final_image, $cropped_rotated_image, 0, 0, $imgX1, $imgY1, $cropW, $cropH, $cropW, $cropH);
// finally output png image
//imagepng($final_image, $output_filename.$type, $png_quality);
        imagejpeg($final_image, $output_filename.$type, $jpeg_quality);
        $response = Array(
        "status" => 'success',
        "url" => base_url(). $output_filename.$type );
        $output=str_replace('temp/', '', $output_filename);
        $file=array(
        'photo'=>$output,
        );
        $this->Logo_model->store_logo($file);
    }
    print json_encode($response);     
}



public function img_save_to_file(){

/*
*   !!! THIS IS JUST AN EXAMPLE !!!, PLEASE USE ImageMagick or some other quality image processing libraries
*/
$imagePath =  "temp/";


$allowedExts = array("gif", "jpeg", "jpg", "png", "GIF", "JPEG", "JPG", "PNG");
$temp = explode(".", $_FILES["img"]["name"]);
$extension = end($temp);

    //Check write Access to Directory

if(!is_writable($imagePath)){
    $response = Array(
        "status" => 'error',
        "message" =>  $imagePath
        );
    print json_encode($response);
    return;
}

if ( in_array($extension, $allowedExts))
{
    if ($_FILES["img"]["error"] > 0)
    {
        $response = array(
            "status" => 'error',
            "message" => 'ERROR Return Code: '. $_FILES["img"]["error"],
            );          
    }
    else
    {

        $filename = $_FILES["img"]["tmp_name"];
        list($width, $height) = getimagesize( $filename );

        move_uploaded_file($filename,  $imagePath . $_FILES["img"]["name"]);

        $response = array(
            "status" => 'success',
            "url" => base_url(). $imagePath.$_FILES["img"]["name"],
            "width" => $width,
            "height" => $height
            );

    }
}
else
{
    $response = array(
        "status" => 'error',
        "message" => 'something went wrong, most likely file is to large for upload. check upload_max_filesize, post_max_size and memory_limit in you php.ini',
        );
}

print json_encode($response);
}

}

/* Location: ./application/controllers/home.php */

Table Schema:

CREATE TABLE IF NOT EXISTS `logo` ( `id` int(11) NOT NULL, `photo` varchar(255) COLLATE utf8_unicode_ci NOT NULL ) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

It actually works fine if it's not connected to the database. Whenever I add these lines:

$output=str_replace('temp/', '', $output_filename);
$file=array('photo'=>$output,);
$this->Logo_model->store_logo($file);

It starts to break saying that it cannot retrieve the post requests. What could be the possible mistake I am doing?

Disclaimer: These codes came from the source files I've downloaded. I wanted to try it first before I actually implement it on the project I'm working on.

i have used your code and the picture after cropping will be store in database and only thing is your Model! you did not specify your "WHERE" statement. after all for "UPDATE" statement you have to have a record in your data base. For instance :

$data = array(
   'your_coloumn_to_update' => 'its value'
)
$this->db->where('your_id',1);
$this->db->update('your_table',$data);

It has worked for me. Check it out.