public static void crop ( File originalImage , File to , int x1 , int y1 , int x2 , int y2 ) { try { BufferedImage source = ImageIO . read ( originalImage ) ; String mimeType = "image/jpeg" ; if ( to . getName ( ) . endsWith ( ".png" ) ) { mimeType = "image/png" ; } if ( to . getName ( ) . endsWith ( ".gif" ) ) { mimeType = "image/gif" ; } int width = x2 - x1 ; int height = y2 - y1 ; // out BufferedImage dest = new BufferedImage ( width , height , BufferedImage . TYPE_INT_RGB ) ; Image croppedImage = source . getSubimage ( x1 , y1 , width , height ) ; Graphics graphics = dest . getGraphics ( ) ; graphics . setColor ( Color . WHITE ) ; graphics . fillRect ( 0 , 0 , width , height ) ; graphics . drawImage ( croppedImage , 0 , 0 , null ) ; ImageWriter writer = ImageIO . getImageWritersByMIMEType ( mimeType ) . next ( ) ; ImageWriteParam params = writer . getDefaultWriteParam ( ) ; writer . setOutput ( new FileImageOutputStream ( to ) ) ; IIOImage image = new IIOImage ( dest , null , null ) ; writer . write ( null , image , params ) ; writer . dispose ( ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } }
Crop an image