使用Codeigniter的Croppic jQuery插件

时间:2016-04-28 14:50:13

标签: php jquery codeigniter

当我正在寻找与codeigniter一起使用的裁剪插件时,我遇到了这个例子:Working Demo

所以我已经下载了源文件,直到我尝试将其连接到数据库。我已按照网站上的说明操作,以下是文件中的代码。

型号:

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

查看:

<!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>

控制器:

class Home扩展了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();

//取消注释下面的行,将裁剪后的图像保存在与原始图像相同的位置。 // $ output_filename = dirname($ imgUrl)。 &#34; / croppedImg _&#34; .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');
    }

//检查对目录的写访问权

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

}

/ *位置:./ application / console / home.php * /

表架构:

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;

如果它没有连接到数据库,它实际上工作正常。每当我添加这些行:

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

它开始破坏说它无法检索帖子请求。我可能犯的错误是什么?

免责声明:这些代码来自我已下载的源文件。在我真正实现它的项目之前,我想先尝试一下。

1 个答案:

答案 0 :(得分:0)

我已经使用了你的代码和裁剪后的图片将存储在数据库中,只有你的模型! 你没有指定你的“WHERE”声明。毕竟,对于“UPDATE”语句,您必须在数据库中有记录。例如:

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

它对我有用。看看吧。