如何在Java中制作圆角图像 [英] How to make a rounded corner image in Java

查看:36
本文介绍了如何在Java中制作圆角图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to make a image with rounded corners. A image will come from input and I will make it rounded corner then save it. I use pure java. How can I do that? I need a function like

public void makeRoundedCorner(Image image, File outputFile){
.....
}

编辑:添加了信息图像.

推荐答案

我建议采用这种方法,获取图像并生成图像并将图像 IO 保持在外部:

I suggest this method that takes an image and produces an image and keeps the image IO outside:

我终于在 Java 2D Trickery:Soft Clipping 作者:Chris Campbell.遗憾的是,这不是 Java2D 开箱即用的一些 RenderhingHint 支持的东西.

I finally managed to make Java2D soft-clip the graphics with the help of Java 2D Trickery: Soft Clipping by Chris Campbell. Sadly, this isn't something Java2D supports out of the box with some 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;
}

这是一个测试驱动程序:

Here's a test driver:

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

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

This it what the input/output of the above method looks like:

输入:

使用 setClip() 的丑陋、锯齿状输出:

Ugly, jagged output with setClip():

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

Nice, smooth output with composite trick:

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

Close up of the corners on gray background (setClip() obviously left, composite right):

这篇关于如何在Java中制作圆角图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆