添加水印的Demo如下,新建工程测试后如遇到问题,可以执行最后图片指示更改即可。
import java.awt.AlphaComposite;
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 java.io.OutputStream;
import javax.imageio.ImageIO;
public class Demo {
public static void main(String[] args) {
// TODO Auto-generated method stub
File file = new File("D://img/1.jpg");
textmark(file,"HELLO WORLD");
}
/**
* @param file
* 图片文件对象
* @param text
* 添加的水印文字
*/
public static void textmark(File file, String text) {
try {
Image image = ImageIO.read(file);
BufferedImage bufferImage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_RGB);// 1.创建图片缓存对象
Graphics2D g = bufferImage.createGraphics(); // 2. 创建Java绘图工具对象
g.drawImage(image, 0, 0, image.getWidth(null), image.getHeight(null), null);//3.将原图通过绘图工具画到图片缓存对象中
g.setFont(new Font("微软雅黑",Font.BOLD,30));
g.setColor(Color.GREEN);//设置水印文字的 字体和颜色
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.3f));
g.drawString(text, 200, 50);//4.将文字添加到缓存图片对象中
g.dispose();
OutputStream os = new FileOutputStream("D://new.jpg");
ImageIO.write(bufferImage, "JPG", os);//通过图片编码工具,将缓存图片保存到本地
} catch (IOException e) {
e.printStackTrace();
}
}
}
报错主要为import javax.imageio.ImageIO;引入错误