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

.....

}

Edit : Added an image for information.

解决方案

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

Edit: 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:

Input:

Ugly, jagged output with setClip():

Nice, smooth output with composite trick:

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值