GithubHelp home page GithubHelp logo

jr-crop's Introduction

jr-crop

A simple ionic plugin to crop your images, inspired by whatsapp and telegram.

  • Specifiy width and height of target
  • Doesn't actually scale the image, only returns a cropped version. Since the quality of images while scaling is inconsistent it's up to the developper to implement this, preferably on the server.
  • Returns a canvas element with the new cropped image.

example

Simple enough, let's get started.

Install the files: bower install jr-crop --save.

Import the static files jr-crop.js and jr-crop.css. Declare jrCrop as a dependency.

.module('myModule', ['ionic', 'jrCrop'])

Inject jr-crop.

.controller('MyController', function($jrCrop) {

Call the crop function to open a new modal where the user can crop this image. Pass in the image url and targetsize. The function will return a promise that resolves when the user is done or fails when the user cancels.

$jrCrop.crop({
    url: url,
    width: 200,
    height: 200
}).then(function(canvas) {
    // success!
    var image = canvas.toDataURL();
}, function() {
    // User canceled or couldn't load image.
});
Changing the title

Additionally you can add a title in the footer.

$jrCrop.crop({
    url: url,
    width: 200,
    height: 200,
    title: 'Move and Scale'
});
Circle mask

Add circle:true to the options to overlay the image with a circle. Note: it won't actually crop the image with a circle, just the visual representation.

$jrCrop.crop({
    url: url,
    circle: true
});
Changing default options.

Overwriting default options can be done as well.
$jrCrop.defaultOptions.template = '<div>...</div>';
$jrCrop.defaultOptions.width = 300;
$jrCrop.defaultOptions.circle = true;

Templates

Custom templates

The template can be overwritten by passing your custom HTML in the options.

$jrCrop.crop({
    url: url,
    width: 200,
    height: 200,
    template: '<div>...</div>'
});
Interpolation Markup

If you configured the expressions of interpolated strings, you can apply this to the template by replacing the markup with your custom markup.

$jrCrop.defaultOptions.template = $jrCrop.defaultOptions.template
    .replace(/{{/g, '<%')
    .replace(/}}/g, '%>');

Examples please!!

I got ya. Run bower install && npm install && npm test and visit localhost:8181. Great, now you can visit this from your phone too. It works best when packaged in cordova, as how you should use ionic anyway.

Support

Though I'm only supporting iOS, I did get reports that it's working well on Android. If it doesn't, feel free to fork and update my codebase. If you just want to leave your thoughts you can reply in the ionic forum topic.

Contributing

Open an issue or create a pull request. Please exclude the /dist files from your pull request.

Release History

  • 2015-11-13  v1.1.2   Overwrite the template through options. Documentation on defaultOptions.
  • 2015-11-12   v1.1.1   Circle mask should not be shown by default.
  • 2015-11-12   v1.1.0   Add circle option to overlay the image with a circle mask.
  • 2015-04-05   v1.0.0   Breaking: jr-crop is now its own module, import it first. Support ionic v1.0.0 release candidate. Setting options will no longer overwrite the default options.
  • 2015-01-04   v0.1.1   Customize Cancel and Choose text.
  • 2014-12-14   v0.1.0   Release on bower, move from grunt to gulp, version numbering in header. Clean up examples and test server. Place the image in the center on initializing. Add maximum scale option. Hide picture overflow in modal at bigger viewport. Add example pictures as static files rather than from url.

jr-crop's People

Contributors

jjimenezlopez avatar jrschild 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

jr-crop's Issues

use interpolateProvider

Could I make a suggestion to use angular's $interpolateProvider instead of assuming {{ }} for templates?

.factory('$jrCrop', [
  '$ionicModal',
  '$rootScope',
  '$q',
  '$interpolate',
function($ionicModal, $rootScope, $q, $interpolateProvider) {
  function i(expr)
  {
    return $interpolateProvider.startSymbol() + expr + $interpolateProvider.endSymbol();
  }
  var template = '<div class="jr-crop modal">' +
                    '<div class="jr-crop-center-container">' +
                      '<div class="jr-crop-img" ng-style="{width: width + \'px\', height: height + \'px\'}"></div>' +
                    '</div>' +
                    '<div class="jr-crop-center-container">' +
                      '<div class="jr-crop-select" ng-class="{\'jr-crop-select-circle\': circle}" style="overflow: hidden" ng-style="{width: width + \'px\', height: height + \'px\'}"></div>' +
                    '</div>' +
                    '<div class="bar bar-footer bar-dark jr-crop-footer">' +
                      '<button class="button button-clear" ng-click="cancel()">'+i('cancelText')+'</button>' +
                      '<div class="title">'+i('title')+'</div>' +
                      '<button class="button button-clear" ng-click="crop()">'+i('chooseText')+'</button>' +
                    '</div>' +
                  '</div>';

Orientation

Theres an issue with orientation on android devices where a portrait image is rotated to landscape in jr-crops canvas.

File Size

The file size is so big that when i try to update picture to the firebase its says firebase exceeded the limit

How do I crop a full-hd image to a resolution that doesn’t fit on the device?

At first sorry for my vague question I'm going to make it more clear.

The final result I want to achieve is sharing (using ngCordova social sharing plugin) an image that has a resolution of 851 x 315 (facebook cover image).

  • I shoot a photo through my Samsung Galaxy S4 (the resolution of the image is/will be 1080 x 1920)

- I accept the image as you need to do that on android (the resolution of the image still is 1080 x 1920)

- I open up the cropper (currently using https://github.com/JrSchild/jr-crop) I set the options to be 851 x 315

The cropper doesn't have the set dimensions because it can't, because the device resolution is too small.
How could I crop a full-hd picture crop it to 851 x 315 and still be able to work with the picture.

To show what the desired result will be I tried the same in Twitter (for iPhone tough), here I'm going to set the image as a new header image that's (1500 x 500).

Image not showing in modal

When i am giving path from cdv storage its not showing image on center or correct. Even i tried to make css correct but unable to set.

Roadmap for next major release

To my knowledge this is still the most desired image cropper for Ionic. Unfortunately I am no longer actively maintaining this plugin. However to make this project future proof and if there is enough support from the community and contributors we can slowly start looking at what this library needs for a next major release.

I am unsure how much time I have to work on this. Before I start planning anything I will require some community feedback on the following items that came up.

  • Fully tested support for Android
  • Extensive unit testing
  • API redesign
    • Expose the controller rather than promise (breaking)
    • A hook/event that emits location/events/updates, (probably broadcast them on the scope)
    • Leak images' current location/scale condition to jr-crop instance
    • Output options: canvas, BLOB (+ image type, image quality), crop-values, instance (contains canvas, toBlob() and crop-values)
  • Internal refactor
    • Fix laggy/jumpy behavior
    • Change the way jr-crop gets instantiated
    • controller.loadImage should be a static/separate method, not instantiated on the prototype
    • Further abstract methods out (use case)
    • Explore options for a single moving image and clip it with a mask
  • Improve documentation and examples
    • How to send large images (.toBlob()/polyfill?) and receive/store them on the server #23
    • Known (security) issues/Troubleshooting
    • How to use the Camera/Photo Library (iOS + Android) with jr-crop
    • API options
    • ?
  • Features
    • Crop surface dependent of screen size
    • Ratio options
    • Crop canvas to circle (Branch)
    • Export to image file (PNG/JPG)
    • Scaling? #17
    • Support other croppable elements than a URL
    • maxScale/minScale option
    • Change overlay color + opacity (also for circle)
    • Allow rotation of image
    • Fix device rotation
    • ?
  • Improve extensibility
  • Take a good look at other implementations like this one and forks to see what they do well/different
  • Ionic v2 support?
  • Desktop support (scale)?

Background color for small image

When I crop a small image (smaller than target), the image is completed with a black background.
I'd rather customize it to white.
This image shows an example:
capture d ecran 2016-09-27 a 09 14 33

Testing in Android

Hi, I've just added two pull requests. I'm writting just to let you know that I am testing jr-crop on two devices:

  • Nexus 5 with Android L 5.0.1
  • OnePlus One with CyanogenMod 11 (with Android 4.4.4)

I'm working with ionic and Cordova. In the first case (Nexus 5) jr-crop works ok. In the second case (OnePlus), with the stock WebView the touch events are not working.

But I have migrated my ionic project recently to Crosswalk, and jr-crop works like a charm in both cases 👍

Image isn't actually cropped

Everything works relatively well. I've run into a few issues like the image being completely off-center as well as the boundaries not working, but all stuff I could fix.

However one thing I noticed is that no matter what I do, the image doesn't actually get cropped. The full image gets returned every single time.

Any ideas?

Cached first photo on IOS9 with ionic

Taking and cropping first photo works great but when i take a second photo, in jr-crop there is still the first photo
On Android everything works great. It's only IOS issue, i tried everything clearing variables, cache. I can take another (one) photo only after closing app.

My code :

navigator.camera.getPicture(onCapturePhoto, onFail, {
                quality: 60,
                encodingType: Camera.EncodingType.JPEG,
                sourceType:Camera.PictureSourceType.CAMERA,
                targetWidth: 1000,
                targetHeight: 1000,
                correctOrientation: true,
                allowEdit: false,
                destinationType: destinationType.FILE_URI
            });

function onCapturePhoto(fileURI) {
            var win = function (r) {
                clearCache();
                retries = 0;
                var response = JSON.parse(r.response);
                sharedProperties.setObject('remoteFileURI', response.path);
                sharedProperties.setObject('isSend', true);
            }

          var fail = function (error) {
                if (retries == 0) {
                      alert( 'retrie!');
                    retries++;
                    setTimeout(function () {
                        onCapturePhoto(fileURI)
                    }, 1000);
                } else {
                    retries = 0;
                    clearCache();
                     alert('Ups. Something wrong happens!');
                }
            }

            sharedProperties.setObject('localFileURI', fileURI);

            $jrCrop.crop({
                url: fileURI,
                width: window.innerWidth - (window.innerWidth * 0.1),
                height: window.innerWidth - (window.innerWidth * 0.1)
            }).then(function (canvas) {
                // success!
                sharedProperties.setObject('croppedImage', canvas.toDataURL());
                clearCache();
                $state.go('nextstep');

            }, function () {
                $state.transitionTo('index');
            });

using $ionicModal.fromTemplateUrl() instead of .fromTemplate()

Hi, just wondering if this is a bug or I've got something wrong here. Basically I wanted to modify the modal crop template html more easily. So I uses $ionicModal.fromTemplateUrl() instead. This function returns a promise with a modal instance, unlike .fromTemplate() which returns the modal instance.
Here are my changes:

      crop: function (options) {
        this.initOptions(options);

        var cropScope = $rootScope.$new(true);

        ionic.Utils.extend(cropScope, this.options);

        $ionicModal.fromTemplateUrl('templates/modals/modal-crop.html', {
          scope: cropScope
        }).then(function (modal) {

          cropScope.modal = modal;
          // Show modal and initialize cropper.
          return cropScope.modal.show().then(function () {
            return (new jrCropController(cropScope)).promise.promise;
          });
        });
      },

This popups a crop modal with my template just fine. However, when I click 'Crop' the promise doesn't resolve(canvas) correctly. It did create a canvas, called .resolve(canvas), but .then(function(canvas) {}) doesn't work some how.

Do you have any ideas?

Image not showing completely in modal

If i take a photo in landscape mode, for example with (700px width) and my phone has 350px width, the plugin modal is not able to show de entire wide image. Is there some way to do that, for example, having a scroll?

Full Image:
img_20160810_175638

Image in jrCrop modal:
screenshot_2016-08-10-18-03-49

Thanks!

How to resize and crop at different size?

I know technically jrcrop is setup to handle profile size images, around 200 to 300 in HxW.
Though in my case I'd like to use it as a way for people to resize and crop images with a larger end size, say around 640x640.

How might I manipulate the canvas size / ratios to get end result size to be larger?

Ultimately the size I'm going for is something close to instagram size with the result.

Thanks for any thoughts!
Justin

Seems it doesn't have canvas size limit check?

So when I'm taking photo and selecting max size that I can select - canvas size is set to values that is not supported by my IPhone.

canvas.width = this.options.width / this.scale;
canvas.height = this.options.height / this.scale;

width is set to 2448, height is set to 3264, which is almost 8MPx and canvas is become broken (empty or something)
http://stackoverflow.com/a/22345796/319375

I'm fixed it by this code

canvas.width = 640;//this.options.width / this.scale;
canvas.height = 640;//this.options.height / this.scale;
-----------
context.drawImage(this.imgFull, -sourceX, -sourceY, this.options.width/this.scale, this.options.height/this.scale, 0, 0, 640, 640);

Is there plans to add some global fix for this? I may add PR later when I figure out how to make it work universally (not just 640x640 I'm interesting in)

Large image Not corpping

I am not able to crop image which size is greater than 10 MB. app crash when i try to crop large image.

`crop()` promise resolved with empty object

Device: iPhone 6
Platform: iOS 9.1
jr-crop version: 1.1.2

For my setup, the image for cropping is a feed from cordova-plugin-camera (via ngCordova), either as a photo selected from the library or a new photo taken at the time. The image shows up fine on the cropping screen (it's even using the new circle feature). The promise returned from crop(), however, is always resolved with empty object, no matter how I pan and/or pinch the circular cropping window.

My code (below) is very straightforward and I have spent hours going through it, so I am quite confident with it. I looked through all the issues (open and closed) and was surprised that no one had encountered the same issue, except for #16. But that issue was reported with vague description and no deep analysis on the problem, so it's difficult to tell whether that's of the same issue as what I am reporting here.

From going through all the issues in this repo, I've got this impression that most of the issues with cordova-plugin-camera involved, if not all, are using Camera.DestinationType.DATA_URL rather than Camera.DestinationType.FILE_URI. The former works with base64-encoded string, while the latter deals with file url (in iOS, it's "file:///...").

Based on the observations above, I have a feeling that this issue has something to do with feeding "jr-crop" with file url.

It would be great if someone who has worked with the Camera.DestinationType.FILE_URI + "jr-crop" combination, regardless working or not, can share his/her experience with me. Please state the device and o/s version you used at the time.

var nativeCameraOpts = {
  quality: 90,
  targetWidth: 2000,
  targetHeight: 2000,
  destinationType: Camera.DestinationType.FILE_URI,
  encodingType: Camera.EncodingType.JPEG,
  allowEdit: false,
  mediaType: Camera.MediaType.PICTURE,
  saveToPhotoAlbum: false,
  correctOrientation: true
};

// `$cordovaCamera` is a wrapper for `cordova-plugin-camera` provided by `ngCordova` module.
$cordovaCamera.getPicture(nativeCameraOpts).then(getPictureSucc);

function getPictureSucc(imageURI) {
  // An example of `imageURI` is "file:///var/mobile/Containers/Data/Application/F0C5EC0D-23EA-4D43-83BE-A850FA89FCEC/tmp/cdv_photo_005.jpg"
  console.log('Picture source URI: ' + imageURI);  

  // For debugging, to make sure the image coming from `cordova-plugin-camera` is valid.
  angular.element('<img />')
    .bind('load', function(e) {
      console.log('Width: ' + this.naturalWidth);
      console.log('Height: ' + this.naturalHeight);
    })
    .prop('src', imageURI);

  $jrCrop.crop({
    url: imageURI,
    width: 320,
    height: 320,
    title: 'Move and Scale',
    circle: true
  }).then(cropPictureSucc);

  function cropPictureSucc(cropped) {
    console.log(cropped); // `cropped` is `{}`

    var dataUrl = cropped.toDataUrl();  // `toDataUrl` does not exist because `cropped` is an empty object.

    // ... send `dataUrl` to the server.
  }
}

Cordova android issue

after downloading plugin
i confused about paths

but i but folders as follows:

jrcrop-->hooks
--->platforms
--->plugins
--->config.xml
--->www----------->angular (folders include js )
--->www----------->angular-ui (folders include js )
--->www----------->css
--->www----------->images(from plugin)
--->www----------->ionic (folders include css and js )
--->www----------->js
--->www----------->uploads
--->www----------->app.js
--->www----------->canvas-to-blob.min.js
--->www----------->index.html
--->www----------->jr-crop.js
--->www----------->jr-crop.css

     put the problem is the plugin not work in android emulator

Change crop box size

i need to change crop box size
and not affect on the image size
i mean is there a way to separate width & height of crop box from width & height of image

Image doesn't process if it isn't "touched" on the crop screen

Hi there!

First of all, I'm a huge fan of this module, it's been working really well for my app.

However, there is one issue (seems to only happen on iOS)...

  1. I select an image to crop.
  2. I'm taken to the crop screen with the image properly displayed.
  3. I don't touch the image or move it in any way, I simply click "Crop" right away.
  4. It doesn't seem like anything gets returned from the canvas.toDataURL() method.

Any thoughts?

Gestures not working with android

Hey,
Thanks for the crop tool. But it does not seem to be working with android for some reason. The gestures are not responding. Little help will be great

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.