Java - Is there any way to make a shaped image?

153 views Asked by At

This may be a weird question, but interesting for me. When we create an image using java, we use:

BufferedImage screencapture = new Robot().createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()) );

But it uses new Rectangle as the image shape, Is there any way to change the image shape? I didn't see any option for that in my eclipse editor. If there is, please give me an example.

2

There are 2 answers

1
Luke Melaia On BEST ANSWER

I don't see any possible way to create different shaped image

Here is a list of the available classes in awt(where we get the image shape). In this list, there aren't any other available shapes.

The method createScreenCapture() takes a java.awt.Rectangle as its sole parameter - so we can only use a Rectangle. There are no overloads to choose from either.

Images themselves are also a rectangle, the computer is unlikely to be able to read any other shape (if it's even possible to create a different shaped image).

3
vlatkozelka On

It all comes down to how to how image sampling works

When images are taken from the real world (or rendered) they are sampled in pixels. The number of those pixels is called spacial resolution: width*height. So obviously images are always represented as a rectangles, so to make the math easier. Just imagine how much extra work would go into rendering images if they were in radial coordinates for example ;)

But, if its the displaying of the image that you are asking about. Then of course you could display them in whatever shape you like. Look at how whats app displays avatars in a circle for example.

How to realize that in Java?

You will have to create your own JComponent, most likely a subclass of JLabel and override the paint method to suit your needs. Something like

public class MyCircularLabel extends JLabel{

BufferedImage image;
//constructors, setters , getters ...

@Override
paint(Graphics g){
super.paint(g);
//initialize some polygon
//draw the image in the shape you prefer here
}

}

I honestly have never tried something like this. But in general that's what you do when you want the GUI to be drawn in a way that's different than the default : you override paint

Also you might want to look at JavaFx, since its more suited for "stylish" UI than Swing is. Look at this example Border-Radius and Shadow on ImageView