图像处理之添加文字水印

在之前图像处理博客中介绍了给图像添加图像水印,比如某些时候我们需要将照片的拍摄时间、位置、天气等信息标注到图像上。今天记录一下一种使用java在图像上添加文字水印的方法,使用的时java自带的Graphics2D。

首先是读取原始图像并创建为Image对象,之后以原图的宽高创建一个空的BufferedImage对象,通过BufferedImage创建一个Graphics2D对象,使用Graphics2D的drawImage方法将原图的Image对象写入BufferedImage中,之后通过Graphics2D的setColor和setFont方法设置字体颜色和字体大小等,最后将String类型的文字信息写入图片。

实现代码:

public BufferedImage addTextToImage(File imageFile,String text,Font font,Color textColor) throws Exception{
		Image srcImage = ImageIO.read(imageFile);
		int width = srcImage.getWidth(null);
		int heigth = srcImage.getHeight(null);
		BufferedImage resultImage = new BufferedImage(width,heigth, BufferedImage.TYPE_INT_RGB);
		Graphics2D graphics2d = resultImage.createGraphics();
		graphics2d.drawImage(srcImage, 0, 0, width,heigth, null);
		graphics2d.setColor(textColor);
		graphics2d.setFont(font);
		int x = width - graphics2d.getFontMetrics(graphics2d.getFont()).charsWidth(text.toCharArray(),0,text.length()) - 50;
		int y = heigth - 50;
		graphics2d.drawString(text, x, y);
		return resultImage;
	}

需要注意的是字体的设置new Font("宋体", Font.PLAIN, 100),最后一个参数为字体大小。Graphics2D写入文字的方法是drawString(text, x, y),这里的x和y是图像上横坐标和纵坐标,以图像左上角为原点,由于字体根据不同大小,在图像上长度会有不同,因此当写入图像右上角或右下角时,需要根据字体长度确定x值,另外字体有一定高度,在y方向上也需要留出一定空间。

接下来进行测试,准备好需要写入的图片和文字,以写入图像拍摄经纬度和高度为例,将文字写入图像右下角,测试代码:

public static void main(String[] args) throws Exception{
		File imageFile = new File("C:\\Users\\admin\\Desktop\\test\\DSC00706.JPG");
		String text = "经度:" + "105.22955605 " + "纬度:" + "32.62005680 " + "高程:" + "846.3";
		BufferedImage image = new TextWaterMarker().addTextToImage(imageFile, text, new Font("宋体", Font.PLAIN, 100), new Color(255,255,0));
		File output = new File("C:\\Users\\admin\\Desktop\\test\\1.JPG");
		ImageIO.write(image, "JPG", output);
	}

运行结果:

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

TheMatrixs

你的鼓励将是我创作的最大动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值