图像处理之添加文字水印
生活随笔
收集整理的這篇文章主要介紹了
图像处理之添加文字水印
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
在之前圖像處理博客中介紹了給圖像添加圖像水印,比如某些時候我們需要將照片的拍攝時間、位置、天氣等信息標注到圖像上。今天記錄一下一種使用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);}運行結果:
總結
以上是生活随笔為你收集整理的图像处理之添加文字水印的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 机器学习入门01-K临近(KNN)的ja
- 下一篇: 机器学习入门02-朴素贝叶斯原理和jav