Answer the question
In order to leave comments, you need to log in
Java how to round an image?
Actually, for myself, I’m sawing a convenient tool for image processing, I came across the fact that I just can’t find a method or even a class that can round an image.
Let's say I have a 500x500 px square.
At the output, I want to get the same picture but with rounded corners,
say, 50px each (the rounds are transparent) and completely round (the rounds are also transparent).
The image is in a BufferedImage.
Dug in the direction of Graphics2D, but did not find anything like it.
Is it just to draw a figure like:
graphics2D.setColor(new Color(1f,1f,1f,1f ));
graphics2D.setBackground(new Color(1f,0f,0f,0f ));
graphics2D.fill(new RoundRectangle2D.Double(0, 0, 500, 500, 500, 500));
graphics2D.drawImage(img, 0, 0, 500, 500, null);
Answer the question
In order to leave comments, you need to log in
In general, I figured it out myself, here's a quick solution, there is something to optimize.
Solution for posterity, may be useful to someone:
private BufferedImage addCorners(BufferedImage tempImg, int cornerRadius){
BufferedImage tempImgRounded = new BufferedImage(500, 500, BufferedImage.TYPE_INT_ARGB);
Graphics2D graphics2D = tempImgRounded.createGraphics();
graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
//graphics2D.setColor(new Color(1f,0f,0f,0f ));
graphics2D.fill(new RoundRectangle2D.Float(0, 0, 500, 500, cornerRadius, cornerRadius));
graphics2D.setComposite(AlphaComposite.SrcAtop);
graphics2D.drawImage(img, 0, 0, null);
return tempImgRounded;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question