How crop some region of image in Java?

Valter Silva picture Valter Silva · Mar 3, 2011 · Viewed 26.4k times · Source

I'm trying do the following code:

private void crop(HttpServletRequest request, HttpServletResponse response){
    int x = 100;
    int y = 100;
    int w = 3264;
    int h = 2448;

    String path = "D:images\\upload_final\\030311175258.jpg";

    BufferedImage image = ImageIO.read(new File(path));
    BufferedImage out = image.getSubimage(x, y, w, h);

    ImageIO.write(out, "jpg", new File(path));

}

But keeps giving me the same error:

java.awt.image.RasterFormatException: (x + width) is outside of Raster
sun.awt.image.ByteInterleavedRaster.createWritableChild(ByteInterleavedRaster.java:1230)
    java.awt.image.BufferedImage.getSubimage(BufferedImage.java:1156)

Where is my mistake ?

Answer

corsiKa picture corsiKa · Mar 3, 2011

My initial guess is that your (x + w) > image.getWidth().

If you print out image.getWidth(), is it 3264? :O

What you're currently doing is this:

<-- 3264 ------>
+--------------+
|    orig      | +-- Causing the problem
|              | V
|   +--------------+
|100| overlap  |   |
|   |          |   |
|   |          |   |
+---|----------+   |
    |              |
    |    out       |
    +--------------+

If you're trying to trim off the top corner of orig, and just get "overlap" then you need to do

BufferedImage out = image.getSubimage(x, y, w-x, h-y);

If you're trying to do this:

+------------------+
|                  |
|  +-----------+   |
|  |           |   |
|  |           |   |
|  |           |   |
|  |           |   |
|  +-----------+   |
|                  |
+------------------+

Then you need to do this:

BufferedImage out = image.getSubimage(x, y, w-2*x, h-2*y);