美文网首页
java给透明图片加水印

java给透明图片加水印

作者: 独孤行者1992 | 来源:发表于2019-08-01 09:48 被阅读0次

    java实现一张透明背景的图片,添加图片水印

    public static void createWaterMarkByIcon(File srcImageFile, File logoImageFile,
                                          File outputImageFile, double degree) {
    
            OutputStream os = null;
            try {
                Image srcImg = ImageIO.read(srcImageFile);
    
                BufferedImage buffImg = new BufferedImage(srcImg.getWidth(null),
                        srcImg.getHeight(null), BufferedImage.TYPE_INT_RGB);
    
                Graphics2D graphics = buffImg.createGraphics();
    
                buffImg = graphics.getDeviceConfiguration().createCompatibleImage(srcImg.getWidth(null), srcImg.getWidth(null), Transparency.TRANSLUCENT);
                graphics = buffImg.createGraphics();
    //            graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    
                int imgWidth = srcImg.getWidth(null);
                int imgHeight = srcImg.getHeight(null);
    
                graphics.drawImage(srcImg.getScaledInstance(srcImg.getWidth(null),
                        srcImg.getHeight(null), Image.SCALE_SMOOTH), 0, 0, null);
    
                ImageIcon logoImgIcon = new ImageIcon(ImageIO.read(logoImageFile));
                Image logoImg = logoImgIcon.getImage();
    
                //旋转
                if (degree>0) {
                    graphics.rotate(Math.toRadians(degree),
                            (double) buffImg.getWidth() / 2,
                            (double) buffImg.getWidth() / 2);
                }
    
                float alpha = 0.7f; // 透明度
                graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
    
                //水印 的位置
                int logoWidth = imgWidth/4;
                int logoHeight = logoWidth*17/20;
    
                graphics.drawImage(logoImg, buffImg.getWidth()-logoWidth, buffImg.getHeight()-logoHeight,logoWidth,logoHeight, null);
    //            graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
                graphics.dispose();
    
                os = new FileOutputStream(outputImageFile);
                // 生成图片
                ImageIO.write(buffImg, "PNG", os);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (null != os)
                        os.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    

    水印位置根据自己实际情况调整。
    参考文档:
    https://blog.csdn.net/gingerredjade/article/details/53193014

    相关文章

      网友评论

          本文标题:java给透明图片加水印

          本文链接:https://www.haomeiwen.com/subject/nwfxdctx.html