java图片水印

如果你不相信努力和时光,那么成果就会是第一个选择辜负你的。不要去否定你自己的过去,也不要用你的过去牵扯你现在的努力和对未来的展望。不是因为拥有希望你才去努力,而是去努力了,你才有可能看到希望的光芒。java图片水印,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com,来源:原文

public class WatermarkTilerWithTransparency {

    public static void main(String[] args) throws Exception {
        // 读取原始图片和水印图片
        BufferedImage sourceImage = ImageIO.read(new File("C:\\000.jpg"));
        BufferedImage watermarkImage = ImageIO.read(new File("C:\\1.jpg"));

        // 创建一个新的BufferedImage用于保存添加了水印的图片
        BufferedImage destinationImage = new BufferedImage(sourceImage.getWidth(), sourceImage.getHeight(),
                BufferedImage.TYPE_INT_ARGB);

        // 获取Graphics2D对象以绘制到destinationImage
        Graphics2D g2d = destinationImage.createGraphics();
        // 设置抗锯齿等属性(可选)
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.drawImage(sourceImage, 20, 50, null);
        
        //水印文字
        setGFont(sourceImage,  "llp", 0.02,g2d);
     

        // 设置水印的透明度(例如设置为50%透明)
        float opacity = 0.1f; 
        g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, opacity));

        // 计算平铺间隔
        int tileSize = watermarkImage.getWidth();
        int xPadding = 20; // 水平间隔
        int yPadding = 10; // 垂直间隔

        // 遍历源图像并绘制透明水印
        for (int x = xPadding; x < destinationImage.getWidth(); x += tileSize + xPadding) {
            for (int y = yPadding; y < destinationImage.getHeight(); y += tileSize + yPadding) {
                g2d.drawImage(watermarkImage, x, y, null);
            }
        }

        // 清理并释放资源
        g2d.dispose();
        // 保存处理后的图片
        ImageIO.write(destinationImage, "PNG", new File("c:\\output_with_transparent_watermark_tiled.png"));
    }
    
    public static void setGFont(BufferedImage sourceImage,String watermarkText,double ratio,Graphics2D g2d) throws IOException {
        Font baseFont = new Font("Arial", Font.BOLD, 18); // 基础字体样式和大小
        Color color = Color.red; // 水印颜色Color.white; 
        // 字体大小与图片宽度的比例ratio = 0.03; 
        int imageWidth = sourceImage.getWidth();
        int imageHeight = sourceImage.getHeight();
        // 计算字体大小
        int fontSize = (int) (ratio * imageWidth);
        Font font = new Font(baseFont.getName(), baseFont.getStyle(), fontSize);
        // 计算水印文本的边界框并定位在右下角
        Rectangle2D rect = font.getStringBounds(watermarkText, g2d.getFontRenderContext());
        int x = (int) (imageWidth - rect.getWidth() - 5); // 留出一点边距
        int y = (int) (imageHeight - rect.getHeight() - 5); // 留出一点边距

        g2d.setFont(font);
        g2d.setColor(color);
        g2d.drawString(watermarkText, x, y);
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/200887.html

(0)
飞熊的头像飞熊bm

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!