/**
* Clips the input image to the specified shape
*
* @param image
* the input image
* @param clipVerts
* list of x, y pairs defining the clip shape, normalised
* to image dimensions (think texture coordinates)
* @return An image, the same size as the input, but only containing
* those pixels that fall inside the clip shape
*/
public static BufferedImage clip( BufferedImage image, float... clipVerts )
{
assert clipVerts.length >= 6;
assert clipVerts.length % 2 == 0;
int[] xp = new int[ clipVerts.length / 2 ];
int[] yp = new int[ xp.length ];
for( int j = 0; j < xp.length; j++ )
{
xp[ j ] = Math.round( clipVerts[ 2 * j ] * image.getWidth() );
yp[ j ] = Math.round( clipVerts[ 2 * j + 1 ] * image.getHeight() );
}
Polygon clip = new Polygon( xp, yp, xp.length );
BufferedImage out = new BufferedImage( image.getWidth(), image.getHeight(), image.getType() );
Graphics g = out.getGraphics();
g.setClip( clip );
g.drawImage( image, 0, 0, null );
g.dispose();
return out;
}
BufferedImage bi = ImageIO.read( new File( "kitten.jpg" ) );
BufferedImage clipped = clip( bi, 0.2f, 0.2f, 0.05f, 0.8f, 0.6f, 0.6f );
ImageIO.write( clipped, "PNG", new File( "clipped.png" ) );