-
package com.qihui.qxj.utils;
-
import java.awt.Color;
-
import java.awt.Font;
-
import java.awt.Graphics2D;
-
import java.awt.Image;
-
import java.awt.image.BufferedImage;
-
import java.io.File;
-
import java.io.FileOutputStream;
-
import java.io.IOException;
-
-
import javax.imageio.ImageIO;
-
public
class Main {
-
public static void main(String[] args) throws IOException {
-
String sourceImg=
"D:\\test.jpg";
//源图片地址
-
String targetImg=
"D:\\123.jpg";
//新存储的地址
-
addWatermark(sourceImg, targetImg);
-
}
-
-
-
/** 设置文字水印
-
* @param sourceImg 源图片路径
-
* @param targetImg 保存的图片路径
-
* @throws IOException
-
*/
-
public static void addWatermark(String sourceImg, String targetImg) throws IOException {
-
File srcImgFile =
new File(sourceImg);
-
Image srcImg = ImageIO.read(srcImgFile);
-
int srcImgWidth = srcImg.getWidth(
null);
-
int srcImgHeight = srcImg.getHeight(
null);
-
int fontSize=
75;
-
Font font =
new Font(
"黑体,Arial",
1, fontSize);
-
BufferedImage bufImg =
new BufferedImage(srcImgWidth, srcImgHeight, BufferedImage.TYPE_INT_RGB);
-
Graphics2D g = bufImg.createGraphics();
-
g.drawImage(srcImg,
0,
0, srcImgWidth, srcImgHeight,
null);
-
g.setColor(Color.BLACK);
-
g.setFont(font);
-
-
//设置水印的坐标
-
g.drawString(
"测试",
3196,
150);
-
g.drawString(
"性别:男",
3196,
150+(
120*
1));
-
g.drawString(
"毕业学校:XXX大学",
3196,
150+(
120*
2));
-
g.setColor(Color.white);
-
font =
new Font(
"黑体,Arial",
1,
120);
-
g.setFont(font);
-
g.drawString(
"广东省深圳(SHENZHEN)",
3000,
2020);
-
g.dispose();
-
// 输出图片
-
FileOutputStream outImgStream =
new FileOutputStream(targetImg);
-
ImageIO.write(bufImg,
"jpg", outImgStream);
-
System.out.println(
"添加水印完成");
-
outImgStream.flush();
-
outImgStream.close();
-
}
-
}
效果图:
可能有些朋友会存在,增加的文字水印没有效果的问题,那可能是图片的宽和高度有问题,需要调整代码的x,y坐标。
注意:图片的左上角为坐标的原点(0,0) 例如测试两个文字的坐标为(3196, 150)
我的原图为4090*2160
点击链接加入群聊【java交流群】:https://jq.qq.com/?_wv=1027&k=5VZxg3k
转载自:https://blog.csdn.net/qq_16855077/article/details/90378173