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 :




30 comments:

  1. thank you so much for your code..

    but i need default crop space through which we can drag how much we need .

    ReplyDelete
    Replies
    1. Thanks for your comment. You can set default crop space. Please see below link
      http://deepliquid.com/content/Jcrop_API.html

      Delete
  2. You are my big friend

    ReplyDelete
  3. I am grtting this error ::
    javax.imageio.IIOException: Can't read input file!
    at javax.imageio.ImageIO.read(Unknown Source)



    ReplyDelete
    Replies
    1. Please check if the path of the image is correct.

      Delete
  4. .jcrop function is not happening because getting a error in java script files like semi colon; is missing...please may i know wt is the problem....

    ReplyDelete
    Replies
    1. Hi Rojit, Plz let me know at what line number you are facing error. Plz provide me your code.

      Delete
  5. Hello, I am trying to crop a image just after uploading the image(Dynamic Images), but this functionality is not working in IE+7 for images whose src is set by $('#imageTagId').attr('src', imgurl), please help ASAP..

    ReplyDelete
  6. Hi Sandeep, Is it working in other browsers? Please send me your code it will review it.

    ReplyDelete
  7. can u just tell me exactly which path I have to provide here--- String absolutePath = "C:/apache-tomcat-5.5.26/webapps/JavaXp/"; please help..

    ReplyDelete
  8. can u just tell me exactly which path I have to provide here--- String absolutePath = "C:/apache-tomcat-5.5.26/webapps/JavaXp/"; please help..
    The cropped image is not displayed ...I can't understand what exactly is the problem..plzz help

    ReplyDelete
    Replies
    1. Path of your web project, where original image is store and where you want to create cropped image for display.

      Delete
  9. Thank you for your code ,but when I cropping image it cropped properly in server , but the browser display older image

    ReplyDelete
  10. i got an error
    javax.imageio.IIOException: Can't read input file!
    can anyone solve it ..

    ReplyDelete
    Replies
    1. @Ankush - Check if the permissions are set properly if you are using linux server. Otherwise try with different image from another location.

      Delete
  11. I am using eclipse with mysql server and images are seeing in the page but only cropper.jsp will gererate the error ..

    ReplyDelete
  12. I GOT THIS ERROR :

    javax.imageio.IIOException: Can't read input file!
    at javax.imageio.ImageIO.read(Unknown Source)
    at org.apache.jsp.cropper_jsp.cropImage(cropper_jsp.java:25)
    at org.apache.jsp.cropper_jsp._jspService(cropper_jsp.java:95)
    at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:405)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:349)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:136)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:526)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1078)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:655)
    at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1566)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1523)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)


    ReplyDelete
  13. is is necessary to put the pool.jpg image in "C:/apache-tomcat-5.5.26/webapps/JavaXp/..
    because i get the crop image after putting the image in the folder..
    else it will show this error..

    ReplyDelete
    Replies
    1. You can provide any temp location in your web project

      Delete
  14. please give me some good solution of it..

    ReplyDelete
  15. can anyone help me to crop uploaded image and save that image mysql database..??

    ReplyDelete
  16. how to crop overlay image in jsp using javascrip or jquerry

    ReplyDelete
  17. thank you so much, best tutorial i have found after hours searching

    ReplyDelete
  18. crop is possible using Apache POI? please explain

    ReplyDelete
  19. Even for me it is giving black image...

    ReplyDelete
  20. My code is

    BufferedImage out = image.getSubimage(x1,y1, w, h);
    ImageIO.write(out, "PNG", new File(destFile));


    I am getting the following error

    SEVERE: Servlet.service() for servlet [com.commercial.controller.SaveCroppedImage] in context with path [/BigBasket] threw exception
    java.awt.image.RasterFormatException: (x + width) is outside of Raster
    at sun.awt.image.ByteInterleavedRaster.createWritableChild(Unknown Source)
    at java.awt.image.BufferedImage.getSubimage(Unknown Source)
    at com.commercial.controller.SaveCroppedImage.doPost(SaveCroppedImage.java:56)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:313)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

    please help....

    ReplyDelete