Sunday, September 2, 2012

Java / JSP : Simple image cropping example


In this article we will see how to crop an image in Java. You are in this page then u might surely know what exactly the Image cropping is, it is nothing but removal of the outer parts of an image  to improve framing, to change aspect ratio etc.

Image cropping can be implemented easily using Java. First lets see the basic example of image cropping. In the below code we have used getSubimage() function of BufferedImage to achive image cropping feature. No need to add any Jar file directly you can run below code and see the output.

Please see the self explanatory java code below.


ImageCropper.java
Output :

Original Image Dimension: 500x370
Cropped Image Dimension: 200x200
Image cropped successfully: C:\Test\croppedImage.jpg

Original image :



Cropped image :


In the above example you have seen how image cropping can be done using Java however the above example have two limitations.

1. If the coordinates are above the limits of an image then it will throw below exception.

Original Image Dimension: 500x370
Exception in thread "main" java.awt.image.RasterFormatException: (y + height) is outside of Raster
at sun.awt.image.ByteInterleavedRaster.createWritableChild(ByteInterleavedRaster.java:1233)
at java.awt.image.BufferedImage.getSubimage(BufferedImage.java:1156)
at com.test.example.ImageCropper.main(ImageCropper.java:17)

2. The exact coordinates cannot be specified by end user as used in above example. End user may need simple drag feature in web page to crop desire section of an image.

To overcome the above limitations we can used Jquery feature in webpage to get the coordinates of the cropping section and pass it to our Java function. Jcrop is the quick and easy way to add image cropping feature to your web application. To know more about Jcrop, click here.

About the example : There is an image.jsp in which you can select the desire section of an image to crop. To achieve this feature you need to add below files as shown in the code. With the help of Jquery we can get the coordinates and pass it to our java function to crop an image. As shown in below codes form is submitted to cropper.jsp which contains the function cropImage(), Ofcourse  you can add the function to java bean, servlet etc as per your requirement.


  • jQuery library - jquery.min.js
  • Jcrop Javascript - jquery.Jcrop.min.js
  • Jcrop CSS stylesheet - jquery.Jcrop.min.css

To download above 3 files, click here.

image.jsp

cropper.jsp
Output :




No comments:

Post a Comment