CodeIgniter 4 Crop Image Before Upload Using Croppie.js

Reading Time: 5 minutes
5,961 Views

Image cropping before upload is a common requirement in web applications, allowing users to precisely select and adjust areas of an image before uploading. In CodeIgniter 4, integrating Croppie.js provides a seamless way to implement image cropping functionality before uploading images.

In this tutorial, we’ll see the comprehensive process of implementing image cropping before upload using Croppie.js in CodeIgniter 4. This functionality empowers developers to offer users a user-friendly interface for selecting and cropping images before they are uploaded to the server.

In this tutorial we will use a jquery plugin Croppie.js. This plugin uses a CSS and JS file. Either you can use these plugin files via CDN link or by putting those files into your application /public folder.

Read More: CodeIgniter 4 How To Read XML Data to JSON Tutorial

Let’s get started.

CodeIgniter 4 Installation

To create a CodeIgniter 4 setup run this given command into your shell or terminal. Please make sure composer should be installed.

composer create-project codeigniter4/appstarter codeigniter-4

Assuming you have successfully installed application into your local system.

Environment (.env) Setup

When we install CodeIgniter 4, we will have env file at root. To use the environment variables means using variables at global scope we need to do env to .env

Either we can do via renaming file as simple as that. Also we can do by terminal command.

Open project in terminal

cp env .env

Above command will create a copy of env file to .env file. Now we are ready to use environment variables.

Enable Development Mode

CodeIgniter starts up in production mode by default. You need to make it in development mode to see any error if you are working with application.

Open .env file from root.

# CI_ENVIRONMENT = production

 // Do it to 
 
CI_ENVIRONMENT = development

Now application is in development mode.

Create Images Folder

Go to /public folder available at application root. Create a folder with name images. We will save generated signature images inside it.

Make sure images folder should have sufficient permission to write content into it.

Read More: CodeIgniter How To Create Environment Variables Example

Create Controller

Next, we need to create a controller file.

php spark make:controller Image --suffix

It will create a file ImageController.php inside /app/Controllers folder.

Open file and write this complete code into it.

<?php

namespace App\Controllers;

use App\Controllers\BaseController;

class ImageController extends BaseController
{
	public function imageCrop()
	{
		return view("image-crop");
	}

	public function imageCropPost()
	{
		$data = $this->request->getVar('image');

        list($type, $data) = explode(';', $data);
        list(, $data)      = explode(',', $data);

        $data = base64_decode($data);
        $image_name = time() . '.png';
        $path =  "images/" . $image_name;

        file_put_contents($path, $data);

        return json_encode(['status' => 1, 'message' => "Image uploaded successfully"]);
	}
}

Create Layout File

Go to /app/Views folder and create a file with name image-crop.php

Open file and write this complete code into it.

<html lang="en">

<head>
    <title>CodeIgniter 4 Crop Image Before Upload Using Croppie.js</title>
    <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/croppie/2.6.2/croppie.min.css">
</head>


<body>
    <div class="container" style="margin-top:30px;">
        <div class="panel panel-primary">
            <div class="panel-heading">CodeIgniter 4 Crop Image Before Upload Using Croppie.js</div>
            <div class="panel-body">
                <div class="row">
                    <div class="col-md-4 text-center">
                        <div id="cropie-demo" style="width:250px"></div>
                    </div>
                    <div class="col-md-4" style="padding-top:30px;">
                        <strong>Select Image:</strong>
                        <input type="file" id="upload">
                        <br />
                        <button class="btn btn-success upload-result">Upload Image</button>
                    </div>


                    <div class="col-md-4">
                        <div id="image-preview"
                            style="background:#e1e1e1;padding:30px;height:300px;"></div>
                    </div>
                </div>


            </div>
        </div>
    </div>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/croppie/2.6.2/croppie.js"></script>

    <script type="text/javascript">

        $uploadCrop = $('#cropie-demo').croppie({
            enableExif: true,
            viewport: {
                width: 200,
                height: 200,
                type: 'circle'
            },
            boundary: {
                width: 300,
                height: 300
            }
        });


        $('#upload').on('change', function() {
            var reader = new FileReader();
            reader.onload = function(e) {
                $uploadCrop.croppie('bind', {
                    url: e.target.result
                }).then(function() {
                    console.log('jQuery bind complete');
                });
            }
            reader.readAsDataURL(this.files[0]);
        });


        $('.upload-result').on('click', function(ev) {
            $uploadCrop.croppie('result', {
                type: 'canvas',
                size: 'viewport'
            }).then(function(resp) {
                $.ajax({
                    url: "<?php echo base_url('crop-submit') ?>",
                    type: "POST",
                    data: {
                        "image": resp
                    },
                    success: function(data) {
                        html = '<img src="' + resp + '" />';
                        $("#image-preview").html(html);
                    }
                });
            });
        });

    </script>

</body>

</html>

Read More: CodeIgniter Integrate Froala WYSIWYG HTML Editor Tutorial

Create Route

Open Routes.php from /app/Config folder and add these route into it.

//...

$routes->get("image-crop", "ImageController::imageCrop");
$routes->post("crop-submit", "ImageController::imageCropPost");

//...

Application Testing

Open project terminal and start development server via command:

php spark serve

URL: http://localhost:8080/image-crop

When we hit Upload button, it will save the cropped image into images folder and also create a image preview at the right sided area.

That’s it.

We hope this article helped you to learn about CodeIgniter 4 Crop Image Before Upload Using Croppie.js in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.