JAVA 给图片添加水印

现在网络上的图片,为了防止其他人盗用,可以添加水印,比如我用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


  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值