Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to make Image cropper using mouse in php and javascript

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 468
    Comment on it

    Hello Reader's

    If you working on Codeingiter and looking for to making the free cropping of image before uploading then this blog is very helpful to you.

    The process of cropping the images is start from loading the preview of images via ajax and then setting the crop frame on it by javascript. The height and width of that frame is sent to PHP image upload function which actually crop the image by those coordinates.

    Now lets get start doing this

    First create a basic image uploader html form with assign the div which will load the selected image via ajax. And its code will go like this:-

    <div class="wrap">
    <h4>Edit Category Banner</h4>
    
    <img id="uploadPreview" style="display:none;"/>
    
                <form action="Controller/UpdateCategoryBannerImg" method="post" enctype="multipart/form-data">
    
                    <input class="btn btn-primary" id="uploadImage" type="file" accept="image/jpeg" name="image" required="" />
                    <input type="hidden" name="id" value="30"  class="form-control" required>
    
                    <input type="hidden" name="current_image" value=""  class="form-control" required>
                    <input type="submit" value="Upload" >
    
                    <!-- hidden inputs -->
                    <input type="hidden" id="x" name="x" />
                    <input type="hidden" id="y" name="y" />
                    <input type="hidden" id="w" name="w" />
                    <input type="hidden" id="h" name="h" />
                </form> 
    </div>

    And for making the preview just add the script as below. Also in this script you have to mention what the crop ratio, Well in my case I want the featured thumbnail so I put the 381:101 ratio. As you run the code above your image will be loaded below the form with this  script and and mouse will create a crop frame in the ratio:-

    <script type="text/javascript">
         
    
    function setInfo(i, e) {
        $('#x').val(e.x1);
        $('#y').val(e.y1);
        $('#w').val(e.width);
        $('#h').val(e.height);
    }
    
    $(document).ready(function() {
        var p = $("#uploadPreview");
    
        // prepare instant preview
        $("#uploadImage").change(function(){
            // fadeOut or hide preview
            p.fadeOut();
    
            // prepare HTML5 FileReader
            var oFReader = new FileReader();
            oFReader.readAsDataURL(document.getElementById("uploadImage").files[0]);
    
            oFReader.onload = function (oFREvent) {
                p.attr('src', oFREvent.target.result).fadeIn();
            };
        });
    
        $('img#uploadPreview').imgAreaSelect({
            // set crop ratio (optional)
            aspectRatio: '384:101',
            onSelectEnd: setInfo
        });
    });
     </script>
    

    Now you have to call some js and css file for this you can download them from the attachments. After completing the part above let's start uploading of images. And it's php code will be go like this:-

        public function UpdateCategoryFeaturedImg()
        {
            $valid_exts = array('jpeg', 'jpg', 'png', 'gif', 'JPG');
            $max_file_size = 200 * 100; 
            $nw = 352;
            $nh = 235; # image with # height
    
            if ($_SERVER['REQUEST_METHOD'] === 'POST') {
              if ( isset($_FILES['image']) ) {
                if (! $_FILES['image']['error'] && $_FILES['image']['size'] < $max_file_size) {
                  $ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));
                  if (in_array($ext, $valid_exts)) {
                      $image_name = 'myCroppedImage'.time(). basename($_FILES["image"]["name"]);
                      $path = 'assets/category_images/featured/'.$image_name;
                      $size = getimagesize($_FILES['image']['tmp_name']);
    
                      $x = (int) $_POST['x'];
                      $y = (int) $_POST['y'];
                      $w = (int) $_POST['w'] ? $_POST['w'] : $size[0];
                      $h = (int) $_POST['h'] ? $_POST['h'] : $size[1];
    
                      $data = file_get_contents($_FILES['image']['tmp_name']);
                      $vImg = imagecreatefromstring($data);
                      $dstImg = imagecreatetruecolor($nw, $nh);
                      imagecopyresampled($dstImg, $vImg, 0, 0, $x, $y, $nw, $nh, $w, $h);
                      imagejpeg($dstImg, $path);
                      imagedestroy($dstImg);
                      
                      $updateCategory['featured_img'] = $image_name;
                      $this->db->where('id', $_POST['id']);                                              
                      $this->db->update('categories', $updateCategory);
                      $file = "assets/category_images/featured/".$_POST['current_image'];
                      unlink($file);
                      $this ->session->set_flashdata('msg', 'Featured updated for category' );
                      redirect($_SERVER['HTTP_REFERER'],'refresh'); 
                      
                    } else {
                      $this ->session->set_flashdata('msg', 'unknown problem!' );
                     
                    } 
                } else {
                   $this ->session->set_flashdata('msg', 'file is too small or large' );
                 }
              } else {
                $this ->session->set_flashdata('msg', 'file not set' );
              }
            } else {
              $this ->session->set_flashdata('msg', 'bad request!' );
            
            }
            redirect($_SERVER['HTTP_REFERER'],'refresh'); 
           }

    In the code above you can see the x, y , h ,w coordinates and height width has been passed to controller's upload image function. Finally the image crop function as below:-

      imagecopyresampled($dstImg, $vImg, 0, 0, $x, $y, $nw, $nh, $w, $h);

    This imagecopyresampled( ) will crop the image portion which you have given. The output of the image will codeingiter destination folder. 

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: