Java操作透明图片并保持背景透明

最近的一个需求,需要对背景为透明的图片加汉字,加完后会出现背景变黑的情况,附上解决方案

public static void pressText2(String sourceImg,String targetImg) {
    try {
        File file = new File(sourceImg);
        File targetfile = new File(targetImg);

        Image image = ImageIO.read(file);
        int width = image.getWidth(null);
        int height = image.getHeight(null);
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = bufferedImage.createGraphics();
        bufferedImage = g.getDeviceConfiguration()
                .createCompatibleImage(width, height, Transparency.TRANSLUCENT);
        g = bufferedImage.createGraphics();

        g.drawImage(image, 0, 0, null);
        g.setColor(Color.BLACK);
        g.drawString("wudididi",20,20);
        ImageIO.write(bufferedImage, "png", targetfile);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

这样新的图片会有加的汉字并且保持背景透明 

你可能感兴趣的:(Java基础)