javaimage-clipping

Clipping polygon image from jpeg image Java


guys!

I have some problem. I need cutting some polygon image from jpg image and save it. In this moment I use OpenSlideJNI.openslide_read_region, but OpenSlide can clip the only rectangle.

Do you have any idea?


Solution

  • The basic code would be:

    // load the image
    
    BufferedImage originalImage = ImageIO.read(...);
    
    // create the polygon
    
    Polygon polygon = new Polygon();
    polygon.addPoint(50, 50);
    polygon.addPoint(150, 50);
    polygon.addPoint(250, 150);
    polygon.addPoint(150, 150);
    
    Rectangle bounds = polygon.getBounds();
    
    // create a transparent clipped image based on the bounds of the Polygon
    
    BufferedImage clippedImage = new BufferedImage(bounds.width, bounds.height, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g = clippedImage.createGraphics();
    
    polygon.translate(-bounds.x, -bounds.y);
    g.setClip(polygon);
    g.drawImage(originalImage, -bounds.x, -bounds.y, null);
    
    // save the clipped image
    
    ImageIO.write(...);
    

    Of course the image will still be rectangular, but the non clipped areas will be transparent.