4

I am aware of BufferedImage.getSubimage However, it cant deal with cropping images that are smaller than the cropping size throwing the exception:

java.awt.image.RasterFormatException: (y + height) is outside raster

I want to be able to crop either a PNG/JPG/GIF to a certain size however if the image is smaller than the cropping area centre itself on a white background. Is there a call to do this? Or do I need to create an image manually to centre the image on if so, how would I go about this?

Thanks

James moore
  • 1,245
  • 4
  • 13
  • 15

1 Answers1

9

You cannot crop an image larger, only smaller. So, you start with the goal dimension,let's say 100x100. And your BufferedImage (bi), let's say 150x50.

Create a rectangle of your goal:

Rectangle goal = new Rectangle(100, 100);

Then intersect it with the dimensions of your image:

Rectangle clip = goal.intersection(new Rectangle(bi.getWidth(), bi.getHeight());

Now, clip corresponds to the portion of bi that will fit within your goal. In this case 100 x50.

Now get the subImage using the value of clip.

BufferedImage clippedImg = bi.subImage(clip,1, clip.y, clip.width, clip.height);

Create a new BufferedImage (bi2), the size of goal:

BufferedImage bi2 = new BufferedImage(goal.width, goal.height);

Fill it with white (or whatever bg color you choose):

Graphics2D big2 = bi2.getGraphics();
big2.setColor(Color.white);
big2.fillRect(0, 0, goal.width, goal.height);

and draw the clipped image onto it.

int x = goal.width - (clip.width / 2);
int y = goal.height - (clip.height / 2);
big2.drawImage(x, y, clippedImg, null);
Devon_C_Miller
  • 16,248
  • 3
  • 45
  • 71
  • 1
    You shouldn't need the intermediate image `clippedImg`. Just do a `big2.drawImage(bi, (bi2.getWidth() - bi.getWidth()) / 2, (bi2.getHeight() - bi.getHeight()) / 2, null);` – j flemm Aug 16 '10 at 19:14
  • That works if the portion of interest is the top-left. It won't work if you want to clip the top or left edge off the original image. However, You might be able do it without the intermediate by using setClip. But I'd have to think a bit how to calculate x & y. – Devon_C_Miller Aug 17 '10 at 15:53
  • @Devon_C_Miller How can it works bi.subImage(clip,1, clip.y, clip.width, clip.height); , subImage method needs 4 parameters(all Integer) ? – user2556079 Oct 07 '15 at 10:25