一、圆角图片

1、代码

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;

public class MakeImageRounded {

	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();
	    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));
	    g2.setComposite(AlphaComposite.SrcAtop);
	    g2.drawImage(image, 0, 0, null);
	    g2.dispose();
	    
	    return output;
	}
	
	public static void main(String[] args) throws Exception{
		BufferedImage icon = ImageIO.read(new File("G:/co.jpg"));
	    BufferedImage rounded = makeRoundedCorner(icon, 30);
	    ImageIO.write(rounded, "png", new File("G:/co-rounded.jpg"));
	}
}

2、效果图

  • 原图

  • 处理之后

二、圆形头像

1、代码

样例代码使用的图片需宽高一致

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;

public class GenerateRoundedAvatar {

	public static void main(String[] args) throws Exception{
		BufferedImage image = ImageIO.read(new File("G:/avatar.jpg"));
		int w = image.getWidth();
	    int h = image.getHeight();
	    int cornerRadius = w;
	    BufferedImage output = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);

	    Graphics2D g2 = output.createGraphics();
	    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));
	    g2.setComposite(AlphaComposite.SrcAtop);
	    g2.drawImage(image, 0, 0, null);
	    g2.dispose();
	    
	    ImageIO.write(output, "png", new File("G:/avatar-rd.jpg"));
	}
}

2、效果图

  • 原图

  • 处理之后

参考资料:

How to make a rounded corner image in Java