Graphics2D 在一张图片上添加一个带有透明背景的图片或绘制透明图片

Graphics2D 在一张图片上添加一个带有透明背景的图片或绘制透明图片

绿林寻猫
2022-01-12 / 0 评论 / 257 阅读 / 正在检测是否收录...

代码实例

        // 读取原图片信息   底图
        //得到文件
        File file = new File("d:\\1.png");
        //文件转化为图片
        Image srcImg = ImageIO.read(file);
        //获取图片的宽
        int srcImgWidth = srcImg.getWidth(null);
        //获取图片的高
        int srcImgHeight = srcImg.getHeight(null);
        // 加水印
        BufferedImage bufImg = new BufferedImage(srcImgWidth, srcImgHeight, BufferedImage.TYPE_INT_RGB);
        Graphics2D gs = bufImg.createGraphics();
 
        
        //得到带有透明背景的图片
        Image ima=ImageIO.read(new File("d:\\2.png"));
        BufferedImage bi=new BufferedImage(ima.getWidth(null),ima.getHeight(null),BufferedImage.TYPE_INT_BGR);
        Graphics2D gg=bi.createGraphics();
        bi= gg.getDeviceConfiguration().createCompatibleImage(ima.getWidth(null), ima.getHeight(null), Transparency.TRANSLUCENT);
        gg = bi.createGraphics();
        gg.drawImage(ima, 0, 0, null);
        gg.dispose();
 
        
        //将透明背景图绘制到底图上
        // 第一参数->设置的内容,后面两个参数->文字在图片上的坐标位置(x,y)
         gs.drawImage(bi, 605, 148,null);
         gs.dispose();
 
        ByteArrayOutputStream bs = new ByteArrayOutputStream();
        ImageOutputStream imOut = ImageIO.createImageOutputStream(bs);
        ImageIO.write(bufImg, "png", imOut);
        InputStream inputStream = new ByteArrayInputStream(bs.toByteArray());
        OutputStream outStream = new FileOutputStream("d:\\3.png");
        IOUtils.copy(inputStream, outStream);
        inputStream.close();
        outStream.close();

绘制透明图片

        int width=256;
        int height=256;
        //创建BufferedImage对象
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        // 获取Graphics2D
        Graphics2D g2d = image.createGraphics();
        // 增加下面代码使得背景透明
        image = g2d.getDeviceConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT);
        g2d.dispose();
        g2d = image.createGraphics();
        // 释放对象
        g2d.dispose();
        // 保存文件
        ImageIO.write(image, "png", new File("D:/test.png"));
0

评论 (0)

取消