How crop some region of image in Java?
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");