现在网络上的图片,为了防止其他人盗用,可以添加水印,比如我用csdn写博文,他就会自动给我上传的图片添加水印。
前段时间写过一篇 JAVA 绘制验证码图像及解决黑色背景问题 ,在这篇的基础上,理解添加水印的功能更加容易。
先上代码示例:
/*****
* 给图片添加文字水印
* @author wjw
*
*/
public class ImageUtils {
public static void main(String[] args) throws IOException {
String inputImagePath = "C:/Users/wjw/Desktop/01.jpg";
String outputPath = "C:/Users/wjw/Desktop/01-add.jpg";
String text = "这张图片属于wjw!";
addTextToImage(inputImagePath, outputPath, text, Color.YELLOW);
}
public static void addTextToImage(String inputImagePath,String outputPath,String text,Color color) throws IOException{
File file = new File(inputImagePath);
Image image = ImageIO.read(file);
BufferedImage bi = new BufferedImage(image.getWidth(null),image.getHeight(null),BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = bi.createGraphics();
g2.drawImage(image, 0, 0, image.getWidth(null), image.getHeight(null), null);
g2.setColor(color);
g2.setFont(new Font("宋体",Font.BOLD,20));
g2.drawString(text, 0, image.getHeight(null));
g2.dispose();
ImageIO.write(bi, "JPG", new FileOutputStream(outputPath));
}
}
运行结果:
未加水印:
加水印后:
说明:
仿照上一篇,把过程简单说一下:
1.初始化画布:加水印和验证码功能一样,都得先有个画布,没画布都白扯。
BufferedImage bi = newBufferedImage(image.getWidth(null),image.getHeight(null),BufferedImage.TYPE_INT_RGB);
2.拿画笔
Graphics2D g2 = bi.createGraphics();
3.画原图片:第三步就是和验证码的那篇的区别了,验证码是在画布上直接挥毫泼墨,draw验证码字符串,而加水印我们首先要将原来的图片画到画布上,才能加水印
g2.drawImage(image, 0, 0, image.getWidth(null), image.getHeight(null), null);
4.加水印:在原图片基础上draw字符串
g2.setColor(color);
g2.setFont(new Font("宋体",Font.BOLD,20));
g2.drawString(text, 0, image.getHeight(null));
5.写出
ImageIO.write(bi, "JPG", new FileOutputStream(outputPath));
过程很容易理解,如有错误,欢迎指正
end