Java implementation to generate watermark photos

Java implementation to generate watermark photos

Java implementation to generate watermark photos


import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;

import javax.imageio.ImageIO;

public class test {
    
    
    public static void main(String[] args) throws IOException {
    
    
        // 定义水印文字
        String watermarkText = "水印文字";

        // 定义水印文字的字体和样式
        Font watermarkFont = new Font("Arial", Font.BOLD, 46);
        AffineTransform watermarkTrans = new AffineTransform();
        watermarkTrans.rotate(Math.toRadians(-45), 0, 0);
        watermarkFont = watermarkFont.deriveFont(watermarkTrans);

        // 定义水印文字的颜色
        Color watermarkColor = Color.WHITE;
        //透明度
        AlphaComposite alpha = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.3f);


        // 获取文件夹路径
        String folderPath = "/Users/local/image";

        try {
    
    
            // 遍历文件夹中的所有照片
            File folder = new File(folderPath);
            File[] files = folder.listFiles(new FilenameFilter() {
    
    
                public boolean accept(File dir, String name) {
    
    
                    return name.toLowerCase().endsWith(".jpg") || name.toLowerCase().endsWith(".jpeg");
                }
            });

            for (File file : files) {
    
    
                // 读取照片
                BufferedImage image = ImageIO.read(file);

                // 创建Graphics2D对象,用于在照片上绘制水印
                Graphics2D g2d = (Graphics2D) image.getGraphics();

                // 设置水印文字的字体和颜色
                g2d.setFont(watermarkFont);
                g2d.setColor(watermarkColor);

                g2d.setComposite(alpha);

                // 计算水印文字的位置
                FontMetrics fontMetrics = g2d.getFontMetrics();
                int textWidth = fontMetrics.stringWidth(watermarkText);
                int textHeight = fontMetrics.getHeight();
                // 计算水印文本的位置
                int x = (image.getWidth() - textWidth) / 2;
                int y = (image.getHeight() - textHeight) / 2;

                // 在照片上绘制水印文字
                g2d.drawString(watermarkText, x, y);
                g2d.dispose();

                // 保存图片
                ImageIO.write(image, "jpg", file);
            }
        }catch (Exception e){
    
    

        }
    }
}

Guess you like

Origin blog.csdn.net/weixin_41902931/article/details/129786938