处理头像将头像变圆背景透明

废话不多说直接上代码

    /**
     * 处理头像
     * @param img
     */
    public static void rotundity_img(String img) {
        try {
            // 读取图片
            BufferedImage bi1 = ImageIO.read(new File(img));
            // 创建一个带透明色的BufferedImage
            BufferedImage image = new BufferedImage(bi1.getWidth(), bi1.getHeight(),
                    BufferedImage.TYPE_INT_ARGB);
            // 创建一个椭圆形的2D图像
            Ellipse2D.Double shape = new Ellipse2D.Double(0, 0, bi1.getWidth(), bi1
                    .getHeight());
            Graphics2D g2 = image.createGraphics();
            image = g2.getDeviceConfiguration().createCompatibleImage(bi1.getWidth(), bi1.getHeight(), Transparency.TRANSLUCENT);
            g2 = image.createGraphics();
    /*        g2.setColor(Color.WHITE);
            g2.fillRect(0, 0, WIDTH, HEIGHT);*/
            g2.setComposite(AlphaComposite.Clear);
            g2.fill(new Rectangle(image.getWidth(), image.getHeight()));
            g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, 1.0f));
            g2.setClip(shape);
            g2.drawImage(bi1, 0, 0, null);
            g2.dispose();
            ImageIO.write(image, "png", new File(img));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

你可能感兴趣的:(java)