Search code examples
javaswingscreenshotawtrobot

How to take a custom shaped screenshot?


For creating screenshots in Java i have been using the java.awt.Robot class' createScreenCapture() method. But i was only able to create screenshots in the Rectangle shape. Now my question is is there any way to take a screenshot of custom shape either by using the Robot class or some other explicit code?

And by the way, for custom shape the screenshot has to be transparent and i am likely to store it in PNG format.

Any answer is appreciated.


Solution

  • is there any way to take a screenshot of custom shape either by using the Robot class or some other explicit code?

    I like Andrew Thompson's solution that shows how to create a shaped image from a rectangular image. See Cut Out Image in Shape of Text.

    You can do this with any shape. For example you can create your own Polygon by doing something like:

    Polygon polygon = new Polygon();
    polygon.addPoint(250, 50);
    polygon.addPoint(350, 50);
    polygon.addPoint(450, 150);
    polygon.addPoint(350, 150);
    g.setClip(polygon);
    g.drawImage(originalImage, 0, 0, null);