
package suiyin;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class Wimg {
//文字水印
public static void main(String[] args) {
//要添加水印的图片
File file = new File("C:\Users\w1663\Pictures\Camera Roll\img.png");
//添加完水印输出的图片
String file1 = "C:\Users\w1663\Pictures\Camera Roll\img1.png";
//水印文字
String st = "你好中国";
//文字颜色
var color = new Color(112, 211, 11, 180);
wimg(file, file1, st, color);
}
public static void wimg(File file, String file1, String st, Color color) {
try {
//读取图片信息
Image t = ImageIO.read(file);
//读取图片的宽度
int w = t.getWidth(null);
//读取图片的高度
int h = t.getHeight(null);
//建立画布开始绘画
BufferedImage bufferedImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
//建立画笔
Graphics2D graphics2D = bufferedImage.createGraphics();
//将原图片的信息画入画布
graphics2D.drawImage(t, 0, 0, w, h, null);
//设置字体属性
Font font = new Font("宋体", Font.PLAIN, 40);
//设置画笔颜色
graphics2D.setColor(color);
//设置画笔字体属性
graphics2D.setFont(font);
//获取水印的指标
var fm = graphics2D.getFontMetrics(font.deriveFont(40f));
//设置字体坐标
int x = w - fm.stringWidth(st) - 10;
int y = h - 20;
//将水印画上
graphics2D.drawString(st, x, y);
//清空画笔释放资源
graphics2D.dispose();
//建立写入文件流
FileOutputStream out = new FileOutputStream(file1);
//将画布内容写入到目标文件中,格式为PNG
ImageIO.write(bufferedImage, "png", out);
//清空缓冲区
out.flush();
//关闭缓冲区
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)