效果:
代码:
private static BufferedImage resizeAndClipToCircle(BufferedImage image, int size) {// 缩小图片BufferedImage resizedImage = new BufferedImage(size, size, BufferedImage.TYPE_INT_ARGB);Graphics2D g2d = resizedImage.createGraphics();g2d.drawImage(image, 0, 0, size, size, null);g2d.dispose();// 裁剪成圆形BufferedImage circularImage = new BufferedImage(size, size, BufferedImage.TYPE_INT_ARGB);Graphics2D g2d2 = circularImage.createGraphics();Ellipse2D.Double ellipse = new Ellipse2D.Double(0, 0, size, size);g2d2.setClip(ellipse);g2d2.drawImage(resizedImage, 0, 0, size, size, null);g2d2.dispose();return circularImage;}
调用:
// 读取头像图片BufferedImage avatarImage = ImageIO.read(new File("D:\\test1\\touxiang.png"));// 缩小第五张图片并裁剪成圆形BufferedImage scaledCircularAvatar = resizeAndClipToCircle(avatarImage, 400);