在之前图像处理博客中介绍了给图像添加图像水印,比如某些时候我们需要将照片的拍摄时间、位置、天气等信息标注到图像上。今天记录一下一种使用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);
}
运行结果: