使用 jcrop 和 CodeIgniter 裁剪图像

Posted

技术标签:

【中文标题】使用 jcrop 和 CodeIgniter 裁剪图像【英文标题】:Crop Images using jcrop with CodeIgniter 【发布时间】:2015-03-29 09:09:12 【问题描述】:

我已经在CodeIgniter 上传了图片。但是当我想使用jcropcodeigniter 裁剪上传的图像时遇到了问题。我尝试了以下不起作用的代码:

控制器 (image_upload.php)

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Image_upload 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 http://codeigniter.com/user_guide/general/urls.html
 */
public function __construct()

    parent::__construct();
    $this->load->model('upload_model');
    $this->load->library('form_validation');
    $this->load->helper('form');
    $this->load->helper('url');        


public function index()

    $this->load->view('index_view');


public function upload()

    if($this->input->post('submit'))
                
        $config['upload_path'] = './assets/images/';
        $config['allowed_types'] = 'gif|jpg|png';
        $config['max_size'] = '1024';
        $config['max_width']  = '1024';
        $config['max_height']  = '768';
        $config['file_name'] = 'test';

        $this->load->library('upload', $config);
        $fiels_name =   "images";
        $this->upload->do_upload($fiels_name);

        $image_path = $this->upload->data();
        $images = $image_path['file_name'];
        // var_dump($images);
        // die();
        $this->load->view('crop_view');
        $this->crop($image_path);
        $this->upload_model->upload($images);
        // redirect('image_upload');                              
            
    else
    
        redirect('image_upload');
    


public function crop($image_path)


    //crop it
    $data['x'] = $this->input->post('x');
    $data['y'] = $this->input->post('y');
    $data['w'] = $this->input->post('w');
    $data['h'] = $this->input->post('h');

    $images = $image_path['file_name'];

    $this->load->library('image_lib');

    $config['image_library'] = 'gd2';
    // $config['library_path'] = '/usr/X11R6/bin/';
    $config['source_image'] = './assets/images/' . $images;
    $config['new_image'] = './assets/images/' . $images.'_'.time();
    die($data['x']);
    $config['width']  = $data['w'];
    $config['height'] = $data['h'];
    $config['x_axis'] = $data['x'];
    $config['y_axis'] = $data['y'];

    $config['maintain_ratio'] = FALSE;
    $config['dynamic_output'] = TRUE;
    $this->image_lib->initialize($config);

    if(!$this->image_lib->crop()) 
        echo $this->image_lib->display_errors();
     else 
        echo "Success";
    



/* End of file image_upload.php */
/* Location: ./application/controllers/image_upload.php */

查看 (index_view.php)

        <!-- Button trigger modal -->
        <button type="button" class="btn btn-primary btn-md" data-toggle="modal" data-target="#myModal">
            Image Upload
            </button>

        <!-- Modal -->
        <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                        <h4 class="modal-title" id="myModalLabel">Crop the image</h4>
                    </div>
                    <div class="modal-body">

                        <?php echo form_open_multipart('image_upload/upload'); ?>
                        <div class="form-group">
                            <label for="images">Upload a profile picture for you</label>
                            <input type="file" id="images" name='images' onchange="loadFile(event)">
                            <p class="help-block">Image must be less than 1MB</p>
                            <img id="image_preview"/>

                        </div>  
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                        <button type="submit" class="btn btn-success" name="submit" value="submit">Upload</button>
                        <?php echo form_close(); ?>
                    </div>
                </div>
            </div>          
        </div>  
    </div>



    <!-- Bootstrap core javascript
    ================================================== -->
    <!-- Placed at the end of the document so the pages load faster -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
    <script src="<?php echo base_url(); ?>assets/js/bootstrap.min.js"></script>
    <script src="<?php echo base_url(); ?>assets/js/jquery.Jcrop.js"></script>
    <script>
        var loadFile = function(event) 
        var reader = new FileReader();
        reader.onload = function()
            var output = document.getElementById('image_preview');
            output.src = reader.result;             
        ;
        reader.readAsDataURL(event.target.files[0]);
      ;
    </script>
    <script>
        $(document).ready(function()
            $("#images").change(function()
                $("#image_preview").css("height": "300px","width": "300px;");
            );
        );
    </script>
</body>

查看 (crop_view.php)

    <script>
        $('#jcrop_target').Jcrop(
        onChange: showPreview,
        onSelect: showCoords,
        aspectRatio: 1,
        addClass: 'custom',
        maxSize: [90,60]
    );

    function showPreview(coords)
    
        var rx = 100 / coords.w;
        var ry = 100 / coords.h;

        $('#preview').css(
            width: Math.round(rx * 500) + 'px',
            height: Math.round(ry * 370) + 'px',
            marginLeft: '-' + Math.round(rx * coords.x) + 'px',
            marginTop: '-' + Math.round(ry * coords.y) + 'px'
        );
    ;

    function showCoords(c)
    
        $('#x').val(c.x);
        $('#y').val(c.y);
        $('#x2').val(c.x2);
        $('#y2').val(c.y2);
        $('#w').val(c.w);
        $('#h').val(c.h);
    ;
    </script>
    <!-- Bootstrap core CSS -->
    <link href="<?php echo base_url(); ?>assets/css/bootstrap.min.css" rel="stylesheet">
    <link href="<?php echo base_url(); ?>assets/css/main.css" rel="stylesheet">
    <link href="<?php echo base_url(); ?>assets/css/jquery.Jcrop.css" rel="stylesheet">
</head>
<body style="background-color: #efe;">
    <div class="container">
<div class="row">
    <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12" id="upload_images">
        <h1>Crop
            <small>Images</small>
        </h1>           
        <?php echo form_open_multipart('image_upload/crop'); ?>
        <div id="uploaded_image">
            <img src="<?php echo base_url();?>assets/images/<?php echo $image_path['file_name'];?>" id="jcrop_target"/>
        </div>
            <div id="uploaded_preview">
            <img src="<?php echo base_url();?>assets/images/<?php echo $image_path['file_name'];?>" id="preview"/>
            </div>
            <input type="hidden" name="x" id="x" />
            <input type="hidden" name="y" id="y" />
            <input type="hidden" name="x2" id="x2" />
            <input type="hidden" name="y2" id="y2" />
            <input type="text" name="w" id="w" />
            <input type="text" name="h" id="h" />
            <input type="hidden" name="image_name" value="<?php echo $image_path['file_name'];?>"/>
            <input type="submit" name="crop_image" value="Crop" />
        <?php echo form_close(); ?> 
    </div>  

</body>

【问题讨论】:

只是想会问你是否尝试过 codeigniter Image Manipulation Class codeigniter.com/user_guide/libraries/image_lib.html 【参考方案1】:

答案是:

if($this->input->post('submit'))
                
        $config['upload_path'] = './assets/images/';
        $config['allowed_types'] = 'gif|jpg|png';
        $config['file_name'] = 'product';
        $config['overwrite'] = FALSE;
        $config['max_size'] = '0';
        $config['max_width']  = '0';
        $config['max_height']  = '0';   

        $this->load->library('upload', $config);

        if(!is_dir($config['upload_path']))
        
            mkdir($config['upload_path'], 0755, TRUE);
        

            if (!$this->upload->do_upload("imgInp"))
             //Upload file
                echo "Unsuccess Upload"; //If error, redirect to an error page
            
            else
            
                $upload_data = $this->upload->data(); 
                $this->load->library('image_lib');

                $image_config['image_library'] = 'gd2';
                $image_config['source_image'] = $upload_data["file_path"] . $upload_data["file_name"];
                $image_config['new_image'] = $upload_data["file_path"] . $upload_data["file_name"];
                $image_config['quality'] = "100%";
                $image_config['maintain_ratio'] = FALSE;  
                //$image_config['dynamic_output'] = TRUE;                      
                $image_config['x_axis'] = $this->input->post('x');
                $image_config['y_axis'] = $this->input->post('y');
                $image_config['width'] = $this->input->post('w');
                $image_config['height'] = $this->input->post('h');

                // var_dump($image_config['x_axis']);
                // var_dump($image_config['y_axis']);
                // var_dump($image_config['width']);
                // var_dump($image_config['height']);
                // die();


               // $this->image_lib->clear();
                $this->image_lib->initialize($image_config); 

                if (!$this->image_lib->crop())
                
                    echo "Unsuccess Crop"; //If error, redirect to an error page
                
                else
                
                    $images = $upload_data['file_name'];
                    $this->upload_model->upload($images);
                    echo "Success";
                    redirect('image_upload');
                          
            
           
    else
    
        redirect('image_upload');
    

【讨论】:

【参考方案2】:

我正在寻找一个这样的例子。 感谢您的怀疑和我的帮助。 我做了一些改变(这对我的工作来说是正确的!!),结果是:

<link rel="stylesheet" type="text/css" href="<?php echo base_url();?>public/lib/jquery.Jcrop.min.css">
<script type="text/javascript" src='<?php echo base_url("public/lib/jquery.Jcrop.min.js");?>'></script>

<?php     include"body.inc";?>

<?php echo form_open_multipart('foto/upload'); ?>
    <div>
        <label for="userfile">Selecione a imagem:</label>
        <input type="hidden" id="x" name='x'value=''></input>
        <input type="hidden" id="y" name='y'value=''></input>
        <input type="hidden" id="w" name='w'value=''></input>
        <input type="hidden" id="h" name='h'value=''></input>
        <input type="file" id="images" name='userfile' required onchange="loadFile(event)">
        <div id=imgPrev>
            <img id="image_preview"/>
        </div>

        <button type="button" class="bt" >Close</button>
        <button type="submit" class="bt" value="submit">Upload</button>
    </div>
<?php echo form_close();?>


<script>
var loadFile = function(event) 
    var reader = new FileReader();
    var output = document.getElementById('image_preview');
    var cwidth = 300;
    var cheight = 400;

    reader.onload = function()            
        output.src = reader.result;
         // initialize jcrop
            $('.jcrop-holder img').attr('src', reader.result);
            $("#image_preview").Jcrop(
                aspectRatio: 3/4,
                setSelect:   [0, 0, cwidth,cheight],
                allowResize: true,
                allowSelect: false,
                onSelect: storeCoords
            );

    ;
//console.log('arquivo:' +event.target.files[0])    
    if(event.target.files[0] !='undefined' && event.target.files[0] != null)
        reader.readAsDataURL(event.target.files[0]);
    else        
        $("#image_preview").attr('src','').data('Jcrop').destroy();
;

function storeCoords(c) 
    jQuery('#x').val(c.x);
    jQuery('#y').val(c.y);
    jQuery('#w').val(c.w);
    jQuery('#h').val(c.h);
console.log('selecionou' +jQuery('#x').val());
;

</script>
<script>
$(document).ready(function()
    $("#image_preview").css("height": "auto","width": "600px");
    $("#imgPrev").css("height": "600px","width": "600px", 'border': '1px solid black','background-color':'gray');
);
</script>

<?php include "footer.inc"; ?></code>

and controller:
<code>
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Foto extends CI_Controller 

 private $uploadDir = './public/uploads/';//diretorio de uploads
 private $definitivoDir = './public/anexo_experimento/';//diretorio definitivo
 private $tempDir =  './public/temp/';//diretorio temporário

public function __construct()

    parent::__construct();
//    $this->load->model('upload_model');
    $this->load->library('form_validation');
    $this->load->helper('form');
    $this->load->helper('url');        


 public function index()
 
  $saida = array('titulo' => 'Incluir foto');
     $this->load->view('foto_index', $saida);
 

 public function upload()
 
   $config['upload_path'] = $this->uploadDir;
   $config['allowed_types'] = 'gif|jpg|png';
   $config['file_name'] = 'foto';
   $config['overwrite'] = true;
   $config['max_size'] = 0;
   $config['max_width']  = '3000';
   $config['max_height']  = '2000';

   $this->load->library('upload', $config);  
   if (!$this->upload->do_upload())
    //Upload file
    echo "Unsuccess Upload"; //If error, redirect to an error page
    echo $this->upload->display_errors();  //passar para flashmsg
   
   else
    if($this->input->post('x') && $this->input->post('y') && $this->input->post('w') && $this->input->post('h'))
     $this->crop($this->upload->data());
  else 
     echo "*****************faltou limites!!!!";
   
  

 private function crop($upload_data)
 
  $this->load->library('image_lib');
  $image_config['image_library'] = 'gd2';
  $image_config['source_image'] = $upload_data["file_path"] . $upload_data["file_name"];
  $image_config['new_image'] = $upload_data["file_path"] . $upload_data["file_name"];
  $image_config['quality'] = "100%";
  $image_config['maintain_ratio'] = FALSE;
  //$image_config['dynamic_output'] = TRUE;
  $image_config['x_axis'] = $this->input->post('x');
  $image_config['y_axis'] = $this->input->post('y');
  $image_config['width'] = $this->input->post('w');
  $image_config['height'] = $this->input->post('h');
  $this->image_lib->initialize($image_config);

  if (!$this->image_lib->crop())
  
   echo "Unsuccess Crop"; //If error, redirect to an error page
  
  else
  
   $images = $upload_data['file_name'];
 //$this->upload_model->upload($images);
   echo "Success";
//   redirect('foto');
  
  

这个网站的缩进很难!!!!

【讨论】:

以上是关于使用 jcrop 和 CodeIgniter 裁剪图像的主要内容,如果未能解决你的问题,请参考以下文章

Chrome 和 IE8 上的 Jcrop 问题 - 仅在页面刷新时才显示裁剪

Carrierwave 和 Jcrop 和 Devise,Jcrop 不裁剪

使用 jcrop 和 java 裁剪图像

Carrierwave 和 Jcrop 不使用 Minimagick 进行裁剪

Rails:使用 Jcrop 和回形针裁剪图像后出现重定向问题

使用 Jcrop 和 Imagemagick 裁剪图像