How crop some region of image in Java?

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 ?

Answers


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);

For those who just want cropping and other basic image manipulation features on your software I recommend to use an image processing library. Usually the implementations are optimized and stable.

Some Java image processing libraries: ImageJ, Marvin, JMagick, JIU, JH Labs, imgscalr.

Another advantage is to keep things simple on your side. You can do a lot of things with just a few lines of code. In the example below, I used Marvin Framework for cropping.

Original:

Cropped:

Source:

MarvinImage image = MarvinImageIO.loadImage("./res/famousFace.jpg");
crop(image.clone(), image, 60, 32, 182, 62);
MarvinImageIO.saveImage(image, "./res/famousFace_cropped.jpg");

Need Your Help

Testing file existence using NSURL

cocoa osx-snow-leopard nsurl core-foundation nsfilemanager

Snow Leopard introduced many new methods to use NSURL objects to refer to files, not pathnames or Core Services' FSRefs.

.Net Where to find the official specification of the BinaryFormatter serialization format?

.net binaryformatter

I'd like to know what is the serialization format of the BinaryFormatter. I found this site which give some good informations, but it was obtained by reverse engineering and it is not complete.