Giter Club home page Giter Club logo

ngimgcrop's Introduction

ngImgCrop

WARNING

THIS PROJECT IS NOT MAINTAINED ANYMORE. You are free to fork it and start a new project.

Overview

Simple Image Crop directive for AngularJS. Enables to crop a circle or a square out of an image.

Screenshots

Circle Crop

Square Crop

Live demo

Live demo on JSFiddle

Requirements

  • AngularJS
  • Modern Browser supporting

Installing

Download

You have two options to get the files:

  • Download ngImgCrop files from GitHub.
  • Use Bower to download the files. Just run bower install ngImgCrop.

Add files

Add the scripts to your application. Make sure the ng-img-crop.js file is inserted after the angular.js library:

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

Add a dependancy

Add the image crop module as a dependancy to your application module:

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

Usage

  1. Add the image crop directive <img-crop> to the HTML file where you want to use an image crop control. Note: a container, you place the directive to, should have some pre-defined size (absolute or relative to its parent). That's required, because the image crop control fits the size of its container.
  2. Bind the directive to a source image property (using image="" option). The directive will read the image data from that property and watch for updates. The property can be a url to an image, or a data uri.
  3. Bind the directive to a result image property (using result-image="" option). On each update, the directive will put the content of the crop area to that property in the data uri format.
  4. Set up the options that make sense to your application.
  5. Done!

Result image

The result image will always be a square for the both circle and square area types. It's highly recommended to store the image as a square on your back-end, because this will enable you to easily update your pics later, if you decide to implement some design changes. Showing a square image as a circle on the front-end is not a problem - it is as easy as adding a border-radius style for that image in a css.

Example code

The following code enables to select an image using a file input and crop it. The cropped image data is inserted into img each time the crop area updates.

<html>
<head>
  <script src="angular.js"></script>
  <script src="ng-img-crop.js"></script>
  <link rel="stylesheet" type="text/css" href="ng-img-crop.css">
  <style>
    .cropArea {
      background: #E4E4E4;
      overflow: hidden;
      width:500px;
      height:350px;
    }
  </style>
  <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>
</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:</div>
  <div><img ng-src="{{myCroppedImage}}" /></div>
</body>
</html>

Options

<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>

image

Assignable angular expression to data-bind to. NgImgCrop gets an image for cropping from it.

result-image

Assignable angular expression to data-bind to. NgImgCrop puts a data uri of a cropped image into it.

change-on-fly

Optional. By default, to reduce CPU usage, when a user drags/resizes the crop area, the result image is only updated after the user stops dragging/resizing. Set true to always update the result image as the user drags/resizes the crop area.

area-type

Optional. Type of the crop area. Possible values: circle|square. Default: circle.

area-min-size

Optional. Min. width/height of the crop area (in pixels). Default: 80.

result-image-size

Optional. Width/height of the result image (in pixels). Default: 200.

result-image-format

Optional. Format of result image. Possible values include image/jpeg, image/png, and image/webp. Browser support varies. Default: image/png.

result-image-quality

Optional. Quality of result image. Possible values between 0.0 and 1.0 inclusive. Default: browser default.

on-change

Optional. Expression to evaluate upon changing the cropped part of the image. The cropped image data is available as $dataURI.

on-load-begin

Optional. Expression to evaluate when the source image starts loading.

on-load-done

Optional. Expression to evaluate when the source image successfully loaded.

on-load-error

Optional. Expression to evaluate when the source image didn't load.

License

See the LICENSE file.

ngimgcrop's People

Contributors

alexk111 avatar mminder avatar omichelsen avatar semonte avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ngimgcrop's Issues

angularjs ver 1.3

It seems not to work with angular ver 1.3.. Do you have a plan to update for ver 1.3?

pinch effect on smartphone to resize the croping area

Hey,
I wasn't able to fully understand your code so I kinda hack my way to allow user to do a pitch effect to resize the cropping part
I have added that code on line 1744 : (after the events handlers)

      var distance1 = false;
            var distance2 = false;
            $document.on('touchend', function (e) {
                if (e.touches.length == 0) return;
                if (e.touches.length == 1) onMouseUp(e);
                else {
                    distance1 = false;
                    distance2 = false;
                }
            });
            elCanvas.on("touchmove", function (e) {
                if (e.touches.length == 0) return;
                if (e.touches.length == 1) onMouseMove(e);
                else {
                    if (!distance1)distance1 = Math.sqrt(Math.pow(e.touches[0].screenX - e.touches[1].screenX, 2) + Math.pow(e.touches[0].screenY - e.touches[1].screenY, 2));
                    else {
                        distance2 = Math.sqrt(Math.pow(e.touches[0].screenX - e.touches[1].screenX, 2) + Math.pow(e.touches[0].screenY - e.touches[1].screenY, 2));
                        var direction = distance1 - distance2 > 0 ? -1 : +1;
                        theArea.setSize(theArea.getSize() + (distance2 - distance1));
                        drawScene();
                        distance1 = Math.sqrt(Math.pow(e.touches[0].screenX - e.touches[1].screenX, 2) + Math.pow(e.touches[0].screenY - e.touches[1].screenY, 2));
                    }
                }
            });

Dynamic width for crop area

Hello,
I implemented the Image Crop directive in my AngularJS mobile application and noticed that many pictures do not fit within the screen of most mobile devices. So I tried to set a "dynamic" width for the crop area:

<div class="cropArea" style="{{setWidth()}}"><img-crop image="myImage" result-image="$parent.resImageDataURI" area-type="square" result-image-size="100" result-image-quality="0.5" result-image-format="image/jpeg"></img-crop></div>

$scope.setWidth = function() { var width = (window.innerWidth > 0) ? window.innerWidth : screen.width; var widthStyle = "width: " + width + "px;"; return widthStyle; };

Furthermore, I limited the height to 200px (via CSS). The problem is that I can crop outside the image.
Exceptions:
IndexSizeError: Index or size is negative or greater than the allowed amount (ng-img-crop.js)
Error: Index or size is negative or greater than the allowed amount (angular.min.js)

How can I fix this?

EDIT: This issue may be related to: #32.
I tested it with: http://www.asesoriait.net/images/IMG_1854.JPG (provided by jack-the-ripper) and the latest version (with exif orientation check & image auto-rotation).

Can't work with cropped image.

fileReader.readAsDataUrl() is throwing an error saying object is not a blob and using atob(image) throws an error saying it is not correctly encoded.

EDIT: You know what I have a lot wrong with my code right now.

EDIT 2: Nope wasn't my code... I can't work with the result image. I see the preview image is working just fine but I can't upload it or read it with file reader or convert with atob(). Also, I can save cropped image preview on my computer which works just fine. Am I missing something or doing something wrong? I'm using angular-file-upload to upload the image (which works on the uncropped image).

Angular ui modal bootstrap hide generated image

When i select an image with the input file, this image is hide behind the modal. if i add z-index and position: absolute on the img-crop element it solve the probleme but i have a float problem.

The code :

<div>Selectionnez une image: <input type="file" id="fileInput" /></div>
<div class="cropArea">
    <img-crop style="z-index:1000000;position:absolute;" image="myImage" result-image="myCroppedImage"></img-crop>
</div>
<div>Image retaillée:</div>
<div><img ng-src="{{myCroppedImage}}" /></div>

Do you have an idea ? thx a lot

typo in cropHost.destroy() leaks event handler

$document.off('mouseup',onMouseMove);
$document.off('touchend',onMouseMove);

should be:

$document.off('mouseup',onMouseUp);
$document.off('touchend',onMouseUp);

If a dozen of images have been cropped already, the leakage makes the GUI (almost) unresponsive.

way for changing colors

Hi.
I need way for changing colors. It's possible?

// Colors
var colors={
areaOutline: '#fff',
resizeBoxStroke: '#fff',
resizeBoxFill: '#444',
resizeBoxArrowFill: '#fff',
resizeCircleStroke: '#fff',
resizeCircleFill: '#444',
moveIconFill: '#fff'
};

Can this work with angular 1.3?

I'm trying to include this module in an Angular 1.3 app but I get evt.target.result as undefined

In my html I have:

<div class="text-center form-group">
    <span class="btn btn-default btn-file">
            Select Image <input type="file" id="fileInput">
    </span>
    </div>
    <div class="text-center form-group">
        <img-crop image="myImage" result-image="croppedImage" area-type="square" result-image-size="250"></img-crop>
    </div>
    <div><img ng-src="{{croppedImage}}" /></div>
</div>

And in my controller I have:

        $scope.myImage='';
        $scope.croppedImage='';

         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); ```

Cross-origin image load denied by Cross-Origin Resource Sharing policy.

Hi, I tried the example code on my local machine. It worked pretty nice when I open the html file directly. However, when I sent the '.html' file via express.js and tried to upload any pictures, I got an error said 'Cross-origin image load denied by Cross-Origin Resource Sharing policy.' and nothing was uploaded. Could anyone give me some help?

CORS question

How can I allow images from other sites to be shown?

Multiple Directive Collision

Hello,

I'm trying to use ngImgCrop in my MEAN.js stack.

However Angular seems to be blocking me due to "Error: [$compile:multidir] Multiple directives [image, imgCrop] asking for new/isolated scope on: "

I've doubled checked that the dependency is working and I'm using the exact same code for as per the example in the demo for the html and I pasted the code from the example controller into an existing controller.

'use strict';

angular.module('users').controller('ProfilePicUploadController', ['$scope','$location', 'Users', 'Authentication',
    function($scope, $location, Users, Authentication) {
        //This is some other stuff
        $scope.user = Authentication.user;
        if (!$scope.user) $location.path('/');

        //This is the exact code as in the demo
        $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);
}]);

And here's the html code

"


upload your profile picture


Select an image file:




Cropped Image:

"

Can anyone help me with this directive error?

result-image not working

Is it from some reason possible please that when I move working code inside angular ui-bootstrap. The result image is not updating anymore on crop?

The code:

<img-crop image="myImage" area-type="square" result-image="myCroppedImage"></img-crop>

compile to better structure

For the sake of ease of deploy, and greater consistency with otgher libraries, why not compile to:
css/ng-img-crop.css
css/ng-img-crop.min.css
js/ng-img-crop.js
js/ng-img-crop.min.js

Take a picture not working

On iPad or iPhone, when I choose "Take a photo" instead of "Use existing" to choose an image to crop,
the crop area will be blank and the image is not loaded.

Could you have a look at this?
Thanks.

Example form upload code not working on iOS device's taken camera image.

On iOS (tested on Chrome iOS and Safari iOS), if I press the "Choose File" button on input form and select take picture, after the picture has been taken the code assign it to variable $scope.myImage as shown in the example. However, on iOS it does not update ngImgCrop with the photo taken. (Choosing from photo library is working fine)

Note that on Android you can take the picture and it will instantly appear on ngImgCrop.

Limit crop area dimensions

Hi,
I would like to have the option to set the width and height of the crop area to limit the customers to my specific size of image,

thanks!

Cross Origin issue

Hello, I am trying to pull an image from Amazon S3 in to the image cropping tool However I am getting the following message:

Error: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.

This pulled the image though, however I am unable to move the cropping tool on it with the following error every time I try:

Uncaught TypeError: Cannot read property '0' of undefined

I have as far as I'm aware set the right configuration on the bucket to allow this to work.

Is this something I can resolve or apart of the crop tool?

Uploading Coupled with Image Crop

This is not a "bug", I just wanted to offer some advice to other developers solving this common use case of uploading and cropping images. For the image crop piece, this library does far better than any others I've found - so thank you for this! The other piece of the puzzle, is a library that handles file uploads really well and can work in harmony with ngImgCrop. The angular-file-upload library is here (not to be confused with the inferior library of the same name): https://github.com/nervgh/angular-file-upload/ and you can find discussion of the integration here: nervgh/angular-file-upload#208 (comment)

And I've created a gist that demonstrates wiring all the pieces together over here: https://gist.github.com/brianfeister/56a1c6c77cd5928a1c53

Touch events broken - jquery stops original event

Hi Alex,

I fixed this by changing:

pageX=e.changedTouches[0].pageX;

to

pageX=e.originalEvent.changedTouches[0].pageX;

(I applied this to all of the touch events)

Im happy to do a pull request if you would like me to? Maybe needs a filter to check for Jquery?

requirejs and touch screen devices

Hi,
thanks for this awesome plugin, it is exactly what I was looking for.

I am having a little trouble getting it to work on touch devices when loading everything via requirejs, and I was wondering if you had any ideas where I am going wrong (everything works as expected on desktop devices):

I created a small repository with a sample code:
https://github.com/paulflo150/breadcrumbs1

Thanks,

Cannot get example to work

Would it be possible to put in a live (i.e fiddle or plunker) example of ngImgCrop working - the example listed fails at the last div line containing src="myCroppedImage"

with the error message:
Failed to load resource: net::ERR_EMPTY_RESPONSE (22:31:45:793 | error, network)
at http://localhost:8383/imagecrop1/myCroppedImage.

I am using angular version v1.3.0 and I has tried it with 1.15 but with same error message. imagecrop1 refers to the name of the project. I can select an image and move and resize the crop area, but the result image is not shown.

Display:none causes crop to reset

I'm using a workflow where the user uploads an image, then once that's successful they move on to the cropper. This works perfectly up until I hit the final stage.

Each stage is basically shown or hidden, all the elements are there in the code at once but only one stage at a time is visible. As soon as you hide the cropper it resets the bounding of the crop and updates the cropped version in the scope accordingly. I've managed to replicate this by simply adding display:none in the element inspector and re-enabling it. I've found a way to script around the issue but it's not as nice or efficient as having this behaviour fixed in the module.

Module is great by the way. Loving it! Thanks for sharing.

Minification (uglify) of the non-minified version causes Angular injection error

I stitch all my vendor files together (unminified versions) and then uglify the result. For this library, this process breaks it. If I use the pre-minified version, everything is fine, but if I uglify it myself, I get the injection (eProvider) error, suggesting that annotation is not correct somewhere in the library. I looked, and although your injected modules do not match case with the function parameters, that seems like it should still work fine.

Filetype gets forced to PNG?

According to the docs the method .toDataURL(), will default to PNG if type is not specified. But type does not seem to be read/set anywhere when an image is loaded?

Please correct me if I'm wrong, but I'd like that my images are not converted if I e.g. load a jpeg?

Support as/for commonJS module & browserify

What's the point of this being on npm if it doesn't comply w/ npm package standards as a commonJS module?

todos:

  • src/dist needs to be built as a commonJS module
  • A main property needs to be added to the package.json
  • npm module re-published

img crop + rotate

do you have any support for image rotation (e.g. rotate 90 deg left/right) ? It seems to me adding css for rotation will ruin the codes for cropping.

Force Image orientation

this issue hapenns with some images, when I upload a file sometimes I het a unwantes 90 degrees rotation

I'm wondering if this could be fixed by applying an exif orientation or if this is an overkill?, I saw that you already doing all image modification in a canvas, is there any way to fix this?

I posted this question in stackoveflow you can view the issue just by download this image
http://www.asesoriait.net/images/IMG_1854.JPG

http://stackoverflow.com/questions/27204309/force-image-orientation-angularjs

thanks

Great things are there but why not aspect ration configurations provided.

@alexk111

Please highlight how we can change or even hard-code aspect ration (2x,y or 2:1).

Also some one mentioned following code as given below but I can not find that code area

else if (areaType === "rectangle" && this._aspectRatio !== null) {
            var canvasH = this._ctx.canvas.height;
            var heightWithRatio = newSize.w / this._aspectRatio;

            if (heightWithRatio < canvasH && se.y < canvasH) {
                newSize.h = newSize.w / this._aspectRatio;
            }
            else {
                if((newSize.h * this._aspectRatio) <= canvasW) {
                    newSize.w = newSize.h * this._aspectRatio;
                }
                else {
                    newSize.h = newSize.w / this._aspectRatio;
                }
            }
        }

Canvas 100px when opened in a modal

Hi, I really enjoy using this plugin but when I use it in a modal the canvas size stay to 100px and I couldn't find a way to fix this issue. Why he doesn't become bigger when I put a big image? Please help to fix this please.

screen shot 2014-11-24 at 16 36 07

How i Initialise the cropper

<div class="cropArea">
        <img-crop image="image.file.image"
                  result-image="cropper.cropperImage"></img-crop>
    </div>

Css crop area:

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

ngImgCrop not working inside angular ui modal

Hi everyone ! I've checked out the example code to implement ngImgCrop and it works fine.
However, if I put the exact same code inside an angular ui modal, it does not work anymore.
When I try to put:
console.log(angular.element(document.querySelector('#fileInput'))); => the element is not found
If I add a setTimeout function with a delay of 1 second, the DOM element is fetched and everything works.
Does anyone have an idea why? I've also tried to fetch the #fileInput element on "document ready" but it does not change anything.

Regards,

Add jQuery support

"e.changedTouches" in "crop-host.js" fails if jquery is included in the angular app using ngImgCrop. Please add jQuery support.

Angulars $document serves as a wrapper for jqlite or jQuery. If jQuery is included in the angular app, $document events are jQuery events (i.e. $document.on('touchmove'...). JQuery events do not contain TouchEvent attributes such as "changedTouches" directly. The TouchEvent is nested under jQueryEvent.originalEvent.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.