Valter Silva
Valter Silva

Reputation: 16656

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 ?

Upvotes: 21

Views: 27328

Answers (2)

Gabriel Archanjo
Gabriel Archanjo

Reputation: 4597

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:
enter image description here

Cropped:
enter image description here

Source:

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

Upvotes: 5

corsiKa
corsiKa

Reputation: 82559

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

Upvotes: 33

Related Questions