package cn.lyc;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Random;
public class ImageIO02 {
//给指定的图片加水印
public static void main(String[] args) {
//图片的路径
String src = "C:\Users\86176\Desktop\p\DM.jpg";
//随机类
Random random = new Random();
try {
//读取这个图片
BufferedImage i = ImageIO.read(new File(src));
//开启画笔
Graphics2D g = i.createGraphics();
//去锯齿
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_DEFAULT);
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
//设置字体文件
Font bmp = Font.createFont(Font.TRUETYPE_FONT, new File("C:\Users\86176\Desktop\\ADKS____.TTF"));
//设置字体格式 大小
Font font = bmp.deriveFont(Font.BOLD,30);
//使用这个字体
g.setFont(font);
//水印内容
String aa = "版权所有:2647871520";
//坐标
int x = 20;
int y = 40;
//设置随机颜色及透明度
g.setColor(new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255),random.nextInt(100)+100));
//把水印文字写进去
g.drawString(aa,x,y);
//关闭画笔
g.dispose();
//输出一个新文件
ImageIO.write(i,"jpg",new FileOutputStream("C:\Users\86176\Desktop\123.jpg"));
} catch (IOException | FontFormatException e) {
e.printStackTrace();
}
}
}
//执行效果: