AngularJS – Image Crop Directive with Resize in Angular 1.x

Many web application has a feature to upload media including images, this can be for any purpose like Uploading some document, uploading screenshots, Updating profile images. To provide a user-friendly interface for uploading we can add an Image crop tool on the client side so that user can crop the desired portion of Images to be uploaded. On another side, it also helps in reducing disk space occupied by images as cropped images have lesser size.

In this post, we will add a Facebook styled image crop UI, where a user can select an image to upload after that it can be cropped resized before uploading on a server.AngularJS – Image Crop Directive with Resize in Angular 1.x

Let’s start…

We are going to use ngImgCrop[] module for crop functionality.

Download and Import Libraries in Index.html

Include ng-img-crop JS and CSS files

Note: Get latest from CDN here

  <script type="text/javascript" src="../angular.min.js"></script>
  <script type="text/javascript" src="../ng-img-crop.js"></script>
  <link rel="stylesheet" href="../ng-img-crop.css"/>

Add ngImgCrop dependency in angular module function.

var myAppModule = angular.module('MyApp', ['ngImgCrop']);

Then update controller code

    angular.module('app', ['ngImgCrop'])
      .controller('Ctrl', function($scope) {
        $scope.myImage='';
        $scope.myCroppedImage='';

        var handleFileSelect=function(evt) {
          var file=evt.currentTarget.files[0];
          var reader = new FileReader();
          reader.onload = function (evt) {
            $scope.$apply(function($scope){
              $scope.myImage=evt.target.result;
            });
          };
          reader.readAsDataURL(file);
        };
        angular.element(document.querySelector('#fileInput')).on('change',handleFileSelect);
      });

Add CSS for Uploaded Image placeholder

   .cropArea {
      background: #E4E4E4;
      overflow: hidden;
      width:500px;
      height:350px;
    }

In HTML add File input, module directive, and preview image tag

  <div>Select an image file: <input type="file" id="fileInput" /></div>
  <div class="cropArea">
    <img-crop image="myImage" result-image="myCroppedImage"></img-crop>
  </div>
  <div>Cropped Image:</div>
  <div><img ng-src="{{myCroppedImage}}" /></div>

In myCroppedImage, it will return base 64 URL which can be saved as PNG image on the server side.

Options

There are various available options, for example, area-type="square"  will change crop area from circle to square.

<img-crop
    image="{string}"
    result-image="{string}"
   [change-on-fly="{boolean}"]
   [area-type="{circle|square}"]
   [area-min-size="{number}"]
   [result-image-size="{number}"]
   [result-image-format="{string}"]
   [result-image-quality="{number}"]
   [on-change="{expression}"]
   [on-load-begin="{expression"]
   [on-load-done="{expression"]
   [on-load-error="{expression"]
></img-crop>

You can check more options here

How to Save base64 URL into PNG Image on Server?

Example JSON data sent from client to PHP server side

{
	"filename":"your_profile_image",
	"imagedata":"data:image/png;base64,iVBORw0KGgoAA..."
}

PHP file to save base64 object into png image on disk

<?php
	define('UPLOAD_DIR', 'uploads/');

	$data = file_get_contents('php://input');
	$parsedData = (array) json_decode($data);

	$image_parts = explode(";base64,", $parsedData['imagedata']);
	$image_type_aux = explode("image/", $image_parts[0]);
	$image_type = $image_type_aux[1];
	$image_base64 = base64_decode($image_parts[1]);
	$file = UPLOAD_DIR . $parsedData['filename'] . '.png';


	if (!is_dir(UPLOAD_DIR) or !is_writable(UPLOAD_DIR)) {
	    echo "Upload Directory Not Found!";
	    exit;
	}

	file_put_contents($file, $image_base64);
	echo "success";
?>

Above PHP code will save file on a defined directory UPLOAD_DIR on server file system.

 

Note: This project is no longer maintained, but still can be used as it most easy to implement in applications.

Subscribe
Notify of
guest
1 Comment
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
Bilu

in mobile section camera pic capture is not working