Crop Image in AngularJS

By | April 17, 2016

In this article, We will learn how to crop a circle or a square out of an image with the help of image Crop directive in AngularJS.

Firstly, add some library or css files in project as below

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="https://cdn.rawgit.com/alexk111/ngImgCrop/master/compile/minified/ng-img-crop.js"></script>
<link href="https://cdn.rawgit.com/alexk111/ngImgCrop/master/compile/minified/ng-img-crop.css" rel="stylesheet" />

Add below code to crop image using angularJS

<script>
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);
});

</script>

Add below code to download the cropable image

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!--download the cropable image-->
<script>
$(document).ready(function () {
$("#download").click(function () {
var imgsrc = $("#newimg").attr('src');
var a = $("<a>").attr('href', imgsrc).attr("download", "cropImg.png").appendTo("body");
a[0].click();
a.remove();
});
});
</script>
<!--This is the css for cropping-->
<style>
.cropArea
{
background: #E4E4E4;
overflow: hidden;
width:500px;
height:350px;
}
</style>
</head>
<body ng-app="app" ng-controller="Ctrl">
<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: <input type="button" id="download" value="Download image" />

</div>
<div><img id="newimg" ng-src="{{myCroppedImage}}" />
</div>

</body>
</html>

Captureoooo

Like it? Share it
  • Gobind Mandal

    Thanks its helpful for me