Search

Image Crop and Upload using Croppie jQuery plugin

post-title

In every social networking website, there is crop and upload functionality available in profile picture. There are many ways you can do it for your web application. One easy and quick way is to use Javascript or jQuery plugin.

Croppie is simple and easy to use jQuery plugin which provides crop the image functionality in easy way before you save images for user.

In this article, we will create Image crop example and also will upload cropped image in PHP with AJAX. So Follow this steps to create image crop example.

First create index.html file with file upload input. In this file we have included croppie.min.css and croppie.min.js CDN files. Also we have included bootstrap for view.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<link href="https://cdnjs.cloudflare.com/ajax/libs/croppie/2.6.4/croppie.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/croppie/2.6.4/croppie.min.js"></script>

Then create <div> tag where you want to generate croppie view.

<div id="croppie-demo"></div>

We have also created image upload for adding image in croppie. And we have added some javascript code to upload image in server and return back cropped images. Here is the full code for index.php file.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Croppie</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/croppie/2.6.4/croppie.min.css" rel="stylesheet">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/croppie/2.6.4/croppie.min.js"></script>
    <style type="text/css">
        #croppie-demo {
            width: 350px;
        }
        #croppie-container {
            padding-top: 30px;
        }
        #croppie-view {
            background: #e1e1e1;
            width: 300px;
            padding: 30px;
            height: 300px;
            margin-top: 30px
        }
    </style>
</head>
<body>
    <div class="container">
        <h2>Croppie</h2>
        <div class="row">
            <div class="col-md-4 text-center">
                <div id="croppie-demo"></div>
              </div>
              <div class="col-md-4" id="croppie-container">
                <strong>Select Image:</strong>
                <br/>
                <input type="file" id="croppie-input">
                <br/>
                <button class="btn btn-success croppie-upload">Upload Image</button>
              </div>
              <div class="col-md-4" style="">
                <div id="croppie-view"></div>
              </div>
        </div>
    </div>
    <script type="text/javascript">
        var croppieDemo = $('#croppie-demo').croppie({
            enableOrientation: true,
            viewport: {
                width: 250,
                height: 250,
                type: 'circle' // or 'square'
            },
            boundary: {
                width: 300,
                height: 300
            }
        });

        $('#croppie-input').on('change', function () { 
            var reader = new FileReader();
            reader.onload = function (e) {
                croppieDemo.croppie('bind', {
                    url: e.target.result
                });
            }
            reader.readAsDataURL(this.files[0]);
        });

        $('.croppie-upload').on('click', function (ev) {
            croppieDemo.croppie('result', {
                type: 'canvas',
                size: 'viewport'
            }).then(function (image) {
                $.ajax({
                    url: "/upload.php",
                    type: "POST",
                    data: {
                        "image" : image
                    },
                    success: function (data) {
                        html = '<img src="' + image + '" />';
                        $("#croppie-view").html(html);
                    }
                });
            });
        });
    </script>
</body>
</html>

The other file is upload.php which is for AJAX upload and return image file html.

<?php

$data = $_POST['image'];

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

$data = base64_decode($data);
$imageName = time().'.png';
file_put_contents('upload/'.$imageName, $data);

You can also pass bellow options.                     

Name Type Default Description
boundary object Size of the container The outer container of the cropper
enableExif boolean false                 Enable exif orientation reading. Tells Croppie to read exif orientation from the image data and orient the image correctly before rendering to the page.                 Requires exif.js             
enableOrientation boolean false Enable or disable support for specifying a custom orientation when binding images
enableResize boolean false Enable or disable support for resizing the viewport area.
enableZoom boolean true Enable zooming functionality
enableOrientation boolean user user
enforceBoundary boolean true Restricts zoom so image cannot be smaller than viewport
mouseWheelZoom boolean true Enable or disable the ability to use the mouse wheel to zoom in and out on a croppie instance.
showZoomer boolean true Hide or Show the zoom slider
viewport object { width: 100, height: 100, type: 'square' }                 The inner container of the coppie. The visible part of the image                 Valid type values: 'square' 'circle'             

You can also use bellow methods to get some useful details:

Name Type Description Parameter
get() object Get the crop points, and the zoom of the image.  
bind({ url, points, orientation, zoom }) Promise Bind an image to the croppie. Returns a promise to be resolved when the image has been loaded and the croppie has been initialized.                 url - URL to image                 points - Array of points that translate into [topLeftX, topLeftY, bottomRightX, bottomRightY]                 zoom - Apply zoom after image has been bound                 orientation - Custom orientation, applied after exif orientation (if enabled). Only works with enableOrientation option enabled (see 'Options').                 Valid options are:                 1 unchanged                 2 flipped horizontally                 3 rotated 180 degrees                 4 flipped vertically                 5 flipped horizontally, then rotated left by 90 degrees                 6 rotated clockwise by 90 degrees                 7 flipped horizontally, then rotated right by 90 degrees                 8 rotated counter-clockwise by 90 degrees             
destroy()   Destroy a croppie instance and remove it from the DOM  
result({ type, size, format, quality, circle }) Promise Get the resulting crop of the image                 type - The type of result to return defaults to 'canvas'                 'base64': returns a the cropped image encoded in base64                 'html': returns html of the image positioned within an div of hidden overflow                 'blob': returns a blob of the cropped image                 'rawcanvas': returns the canvas element allowing you to manipulate prior to getting the resulted image                 size - The size of the cropped image defaults to 'viewport'                 'viewport': the size of the resulting image will be the same width and height as the viewport                 'original': the size of the resulting image will be at the original scale of the image                 {width, height} an object defining the width and height. If only one dimension is specified, the other will be calculated using the viewport aspect ratio.                 format - Indicating the image format.                 Default: 'png'                 Valid values: 'jpeg' | 'png' | 'webp'                 quality - Number between 0 and 1 indicating image quality.                 Default: 1                 circle - force the result to be cropped into a circle                 Valid Values: true | false             
rotate(degrees)   Rotate the image by a specified degree amount. Only works with enableOrientation option enabled (see 'Options'). degrees - Valid Values:90, 180, 270, -90, -180, -270
setZoom(value)   Set the zoom of a Croppie instance. The value passed in is still restricted to the min/max set by Croppie. value a floating point to scale the image within the croppie. Must be between a min and max value set by croppie.

Croppie also triggers bellow method.

update(croppie)Croppie
Triggered when a drag or zoom occurs

$('.croppie').on('update.croppie', function(ev, cropData) {
    // your code...
});

For more example, see official site demo. I hope you liked this article.