Learn How Crop Image While Uploading With Jquery In PHP

admin_img Posted By Bajarangi soft , Posted On 16-09-2020

Cropping is an action to cut a selected portion from the original image.  In this, we are going to create a crop tool in a PHP web application to crop images using jQuery and save through ajax. I have use the cropper.min.js to implement dynamic image cropping functionality.

cropped_image

Let's learn,

1.Create file to upload image as cropimage.php.
2.Implement html code in cropimage.php file to upload image .


 initial page that loads the original image. The user can select image and  manage crop boundary by using the mouse drag   events. 

<html>
<head>
    <title>Crop Image and Upload using JQuery with PHP Ajax</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container ">
    <div class="text-center">
        <h1>Crop Image and Upload using JQuery with PHP Ajax</h1>
    </div>
    <br>
    <h4>Upload image , Crop image and save image</h4>
    <div class="well">
        <div class="box">
            <input type="file" id="file-input" accept="image/*">
        </div>
        <div class="box">
            <div class="col-md-6 ">
                <div class="messgae">
                </div>
            </div>
        </div>
        <div class="box-2">
            <div class="result"></div>
        </div>
        <div class="box-2 img-result hide">
            <img class="cropped" src="" alt="">
        </div>
        <div class="box">
            <div class="options hide">
                <input type="hidden" class="img-w" value="300" min="100" max="1200"/>
            </div>
            <button class="btn btn-primary save hide">Save</button>
        </div>
        <br>
    </div>
</div>
</body>
</html>


3. Include this links for cropping image in cropimage.php.

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/cropper/2.3.4/cropper.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/0.8.1/cropper.min.js"></script>


4.Create jquery functions in cropimage.php to handles the crop area selection and the crop action events.

the original image will be loaded on a landing page. We can select the crop area by using the mouse drag events. Once the crop area is selected, then it can be manipulated by changing the selected dimensions. when save button’s click it will preview the cropped image . 

$(document).ready(function () {
    // vars
    let result = document.querySelector('.result'),
        img_result = document.querySelector('.img-result'),
        img_w = document.querySelector('.img-w'),
        img_h = document.querySelector('.img-h'),
        options = document.querySelector('.options'),
        save = document.querySelector('.save'),
        cropped = document.querySelector('.cropped'),
        cropper = '';

    // on change show image with crop options
    $("#file-input").change(function (e) {
        if (e.target.files.length) {
            const reader = new FileReader(); // start file reader
            reader.onload = (e) => {
                if (e.target.result) {
                    let img = document.createElement('img');// create new image
                    img.id = 'image';
                    img.src = e.target.result
                    result.innerHTML = '';   // clean result before
                    result.appendChild(img);  // append new image
                    save.classList.remove('hide'); // show save btn and options
                    options.classList.remove('hide');  // init cropper
                    cropper = new Cropper(img);
                }
            };
            reader.readAsDataURL(e.target.files[0]);
        }
    });
    $(".save").click(function (e) {
        e.preventDefault();
        let imgSrc = cropper.getCroppedCanvas({ // get result to data uri
            width: img_w.value // input value
        }).toDataURL();
        cropped.classList.remove('hide');// remove hide class of img
        img_result.classList.remove('hide');// show image cropped
        cropped.src = imgSrc;
        $.ajax({
            url: "cropandsave.php",
            type: "POST",
            data: {"image": imgSrc},
            success: function (data) {
                console.log(data);
                $(".messgae").html('<div class=\'container\'><div class=\"alert icon-alert with-arrow alert-success form-alter\" role=\"alert\" style="width: 85%;">\n<i class=\"fa fa-fw fa-check-circle\"></i>\n<strong> Success ! ' +
                    '</strong> <span class=\"success-message\">Cropped Image  Uplaoded Successfully </span>\n</div></div><br>');
            }
        });
    });

});


5.after image cropped we want to save that image  in folder so that we need to create php file as cropandsave.php .

send image in base64 format and this image format we will send to php script by using Ajax. In PHP script we have use file_put_contents() function, this function will save cropped image.
 

<?php

//cropandsave.php

if(isset($_POST["image"]))
{
    $data = $_POST["image"];

    $image_array_1 = explode(";", $data);

    $image_array_2 = explode(",", $image_array_1[1]);

    $data = base64_decode($image_array_2[1]);

    $imageName = time() . '.jpg';

    file_put_contents("upload/$imageName", $data);

    echo 'done';
}
?>


6.Complete Code to Crop Image and Upload using JQuery with PHP Ajax:
 

<html>
<head>
    <title>Crop Image and Upload using JQuery with PHP Ajax</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/cropper/2.3.4/cropper.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/0.8.1/cropper.min.js"></script>
</head>
<style>
    .box {
        padding: 0.5em;
        width: 100%;
        margin: 0.5em;
    }

    .box-2 {
        margin-top: 62px;
        padding: 0.5em;
        width: calc(100% / 2 - 1em);
    }

    .hide {
        display: none;
    }

    img {
        max-width: 100%;
    }
</style>
<body>
<div class="container ">
    <div class="text-center">
        <h1>Crop Image and Upload using JQuery with PHP Ajax</h1>
    </div>
    <br>
    <h4>Upload image , Crop image and save image</h4>
    <div class="well">
        <div class="box">
            <input type="file" id="file-input" accept="image/*">
        </div>
        <div class="box">
            <div class="col-md-6 ">
                <div class="messgae">
                </div>
            </div>
        </div>
        <div class="box-2">
            <div class="result"></div>
        </div>
        <div class="box-2 img-result hide">
            <img class="cropped" src="" alt="">
        </div>
        <div class="box">
            <div class="options hide">
                <input type="hidden" class="img-w" value="300" min="100" max="1200"/>
            </div>
            <button class="btn btn-primary save hide">Save</button>
        </div>
        <br>
    </div>
    <div>
    </div>
</div>
</body>
<script>
    $(document).ready(function () {
        // vars
        let result = document.querySelector('.result'),
            img_result = document.querySelector('.img-result'),
            img_w = document.querySelector('.img-w'),
            img_h = document.querySelector('.img-h'),
            options = document.querySelector('.options'),
            save = document.querySelector('.save'),
            cropped = document.querySelector('.cropped'),
            cropper = '';

        // on change show image with crop options
        $("#file-input").change(function (e) {
            if (e.target.files.length) {
                const reader = new FileReader(); // start file reader
                reader.onload = (e) => {
                    if (e.target.result) {
                        let img = document.createElement('img');// create new image
                        img.id = 'image';
                        img.src = e.target.result
                        result.innerHTML = '';   // clean result before
                        result.appendChild(img);  // append new image
                        save.classList.remove('hide'); // show save btn and options
                        options.classList.remove('hide');  // init cropper
                        cropper = new Cropper(img);
                    }
                };
                reader.readAsDataURL(e.target.files[0]);
            }
        });
        $(".save").click(function (e) {
            e.preventDefault();
            let imgSrc = cropper.getCroppedCanvas({ // get result to data uri
                width: img_w.value // input value
            }).toDataURL();
            cropped.classList.remove('hide');// remove hide class of img
            img_result.classList.remove('hide');// show image cropped
            cropped.src = imgSrc;
            $.ajax({
                url: "cropandsave.php",
                type: "POST",
                data: {"image": imgSrc},
                success: function (data) {
                    console.log(data);
                    $(".messgae").html('<div class=\'container\'><div class=\"alert icon-alert with-arrow alert-success form-alter\"                                           
role=\"alert\" style="width: 85%;">\n<i class=\"fa fa-fw fa-check-circle\"></i>\n<strong> Success ! ' +                       
                        '</strong> <span class=\"success-message\">Cropped Image  Uplaoded Successfully </span>\n</div></div><br>');
                }
            });
        });

    });

</script>
</html>

Related Post