如何在Java中创建圆角图像

Ali*_*vut 17 java image border image-processing

我想制作一个圆角的图像.图像将来自输入,我将使其圆角然后保存.我使用纯java.我怎样才能做到这一点?我需要一个像这样的功能

public void makeRoundedCorner(Image image, File outputFile){
.....
}
Run Code Online (Sandbox Code Playgroud)

架构

编辑:添加了图像以供参考.

Phi*_*art 29

我建议这种方法拍摄图像并生成图像并将图像IO保持在外面:

编辑:我终于设法使Java2D软件剪辑图形借助于Java 2D Trickery: Chris Clipping软剪辑.遗憾的是,这不是Java2D支持开箱即用的东西RenderhingHint.

public static BufferedImage makeRoundedCorner(BufferedImage image, int cornerRadius) {
    int w = image.getWidth();
    int h = image.getHeight();
    BufferedImage output = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);

    Graphics2D g2 = output.createGraphics();

    // This is what we want, but it only does hard-clipping, i.e. aliasing
    // g2.setClip(new RoundRectangle2D ...)

    // so instead fake soft-clipping by first drawing the desired clip shape
    // in fully opaque white with antialiasing enabled...
    g2.setComposite(AlphaComposite.Src);
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2.setColor(Color.WHITE);
    g2.fill(new RoundRectangle2D.Float(0, 0, w, h, cornerRadius, cornerRadius));

    // ... then compositing the image on top,
    // using the white shape from above as alpha source
    g2.setComposite(AlphaComposite.SrcAtop);
    g2.drawImage(image, 0, 0, null);

    g2.dispose();

    return output;
}
Run Code Online (Sandbox Code Playgroud)

这是一个测试驱动程序:

public static void main(String[] args) throws IOException {
    BufferedImage icon = ImageIO.read(new File("icon.png"));
    BufferedImage rounded = makeRoundedCorner(icon, 20);
    ImageIO.write(rounded, "png", new File("icon.rounded.png"));
}
Run Code Online (Sandbox Code Playgroud)

这就是上面方法的输入/输出:

输入:

输入图像

丑陋,锯齿状的输出setClip():

与setclip混在一起

使用复合技巧的漂亮,流畅的输出:

顺利的复合技巧

关闭灰色背景上的角落(setClip()显然左,复合右):

在灰色bacjground的特写镜头角落