M
M
mr_serg772017-07-16 03:11:32
Java
mr_serg77, 2017-07-16 03:11:32

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));

Or draw an image, but do not set the shape: Tell me in which direction to dig? Maybe there is a third party for this, if there is no such thing in the jdk?
graphics2D.drawImage(img, 0, 0, 500, 500, null);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
mr_serg77, 2017-07-16
@mr_serg77

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 question

Ask a Question

731 491 924 answers to any question