Friday, September 19, 2014

GWT Image Cropper

In a previous project where the client was GWT based (in combination with GWTP and Errai) we needed an image cropping component. One of the standard widgets you need in nearly every second project and which is not provided by GWT as a pre-baked UI component. The ones I found on open source repositories I didn't like too much for the lack of documentation, huge parts of spaghetti code, lots of functionalities we didn't need or the combination of all those reasons. Wrapping an existing JS component was not an option, we didn't want to depend on another library. So I decided to implement a GWT only based cropper which might come handy for someone else too.

The inspiration on how it should behave was coming from Jira, the issue tracker we just migrated to back then. I had a look at the responsible DOM elements and how the adapt upon user interaction and tried to implement the cropping behaviour the same way. The idea is to create an outer div showing the image as background and three child divs: one for the glass (area to crop), one for the selection (area to clip) and one for adding the four resize handles to the corner of the selection.

The ImageCropper class takes care of registering the needed handlers, loading the source image and adding the selection component. A LoadHandler is used to size the div showing the background image correctly. To make this work on IE the image needs to be visible otherwise we get 0 for the height and width.


The abstract ResizeHandle contains the base logic for styling the handles and capturing mouse events. The calculation of how the selection should be adapted (getScaledYDelta() and getScaledXDelta()) is delegated to the concrete implementations of the handlers which are instantiated in the SelectionChooser class.


Besides creating the handlers the SelectionChooser class is also responsible of creating the glass and the clipping area as well as adapting the sizes and positions of them on user input.


I didn't test the implementation on all different browsers and versions since the application was used only on Chrome and Firefox (lucky us...). It should though work on IE10 as well when I remember correctly.

On the back end side of things we used Thumbnailator to do the actual cropping. With its fluent API the process of manipulating images becomes straightforward compared to using Java's 2D API along with other techniques.



No comments:

Post a Comment