Java image crop

I know BufferedImage.getSubimage However, it has nothing to do with cropping images that are smaller than the cropping size that throws an exception:

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

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

thanks

+4
source share
1 answer

You cannot crop an image anymore, only less. So, you start by measuring the target, say 100x100. And your BufferedImage ( bi ), say 150x50.

Create a rectangle of your goal:

 Rectangle goal = new Rectangle(100, 100); 

Then cross it with the dimensions of your image:

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

Now the clip matches the bi part that will fit your goal. In this case, 100x50.

Now get subImage using the clip value.

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

Create a new BufferedImage ( bi2 ) goal size:

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

Fill it with white (or any other bg color):

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

and draw a cropped image on it.

 int x = goal.width - (clip.width / 2); int y = goal.height - (clip.height / 2); big2.drawImage(x, y, clippedImg, null); 
+9
source

All Articles