Java implements adding image watermarks and text watermarks
Mar 12, 2021 am 11:34 AMWe often see watermarks of certain companies or brands on some pictures or pictures, so can we add watermarks to our favorite pictures or files ourselves? The answer is of course no problem.
Let’s take a look at the picture watermark first:
----------------------------Picture watermark ----------------------------
1. Add text watermark
import?java.awt.Color; import?java.awt.Font; import?java.awt.Graphics2D; import?java.awt.Image; import?java.awt.image.BufferedImage; import?java.io.File; import?java.io.FileOutputStream; import?javax.imageio.ImageIO; /** ?*?給圖片添加文字水印 ?*? ?*?@author?liqiang ?* ?*/ public?class?WaterMarkUtils?{ ????/** ?????*?@param?args ?????*/ ????public?static?void?main(String[]?args)?{ ????????//?原圖位置,?輸出圖片位置,?水印文字顏色,?水印文字 ????????new?WaterMarkUtils().mark("C:/Users/liqiang/Desktop/圖片/kdmt.jpg",?"C:/Users/liqiang/Desktop/圖片/kdmt1.jpg", ????????????????Color.red,?"圖片來源:XXX"); ????} ????/** ?????*?圖片添加水印 ?????*? ?????*?@param?srcImgPath ?????*????????????需要添加水印的圖片的路徑 ?????*?@param?outImgPath ?????*????????????添加水印后圖片輸出路徑 ?????*?@param?markContentColor ?????*????????????水印文字的顏色 ?????*?@param?waterMarkContent ?????*????????????水印的文字 ?????*/ ????public?void?mark(String?srcImgPath,?String?outImgPath,?Color?markContentColor,?String?waterMarkContent)?{ ????????try?{ ????????????//?讀取原圖片信息 ????????????File?srcImgFile?=?new?File(srcImgPath); ????????????Image?srcImg?=?ImageIO.read(srcImgFile); ????????????int?srcImgWidth?=?srcImg.getWidth(null); ????????????int?srcImgHeight?=?srcImg.getHeight(null); ????????????//?加水印 ????????????BufferedImage?bufImg?=?new?BufferedImage(srcImgWidth,?srcImgHeight,?BufferedImage.TYPE_INT_RGB); ????????????Graphics2D?g?=?bufImg.createGraphics(); ????????????g.drawImage(srcImg,?0,?0,?srcImgWidth,?srcImgHeight,?null); ????????????//?Font?font?=?new?Font("Courier?New",?Font.PLAIN,?12); ????????????Font?font?=?new?Font("宋體",?Font.PLAIN,?20); ????????????g.setColor(markContentColor);?//?根據(jù)圖片的背景設(shè)置水印顏色 ????????????g.setFont(font); ????????????int?x?=?srcImgWidth?-?getWatermarkLength(waterMarkContent,?g)?-?3; ????????????int?y?=?srcImgHeight?-?3; ????????????//?int?x?=?(srcImgWidth?-?getWatermarkLength(watermarkStr,?g))?/?2; ????????????//?int?y?=?srcImgHeight?/?2; ????????????g.drawString(waterMarkContent,?x,?y); ????????????g.dispose(); ????????????//?輸出圖片 ????????????FileOutputStream?outImgStream?=?new?FileOutputStream(outImgPath); ????????????ImageIO.write(bufImg,?"jpg",?outImgStream); ????????????outImgStream.flush(); ????????????outImgStream.close(); ????????}?catch?(Exception?e)?{ ????????????e.printStackTrace(); ????????} ????} ????/** ?????*?獲取水印文字總長度 ?????*? ?????*?@param?waterMarkContent ?????*????????????水印的文字 ?????*?@param?g ?????*?@return?水印文字總長度 ?????*/ ????public?int?getWatermarkLength(String?waterMarkContent,?Graphics2D?g)?{ ????????return?g.getFontMetrics(g.getFont()).charsWidth(waterMarkContent.toCharArray(),?0,?waterMarkContent.length()); ????} }
Result:
2. Add image watermark to the picture
import?java.awt.AlphaComposite; import?java.awt.Graphics2D; import?java.awt.Image; import?java.awt.RenderingHints; import?java.awt.image.BufferedImage; import?java.io.File; import?java.io.FileOutputStream; import?java.io.OutputStream; import?javax.imageio.ImageIO; import?javax.swing.ImageIcon; /** ?*?給圖片添加圖片 ?*? ?*?@author?liqiang ?* ?*/ public?class?WaterMarkUtils?{ ????/** ?????*?@param?args ?????*/ ????public?static?void?main(String[]?args)?{ ????????String?srcImgPath?=?"C:/Users/liqiang/Desktop/圖片/kdmt.jpg"; ????????String?iconPath?=?"C:/Users/liqiang/Desktop/圖片/qlq.jpeg"; ????????String?targerPath?=?"C:/Users/liqiang/Desktop/圖片/qlq1.jpeg"; ????????String?targerPath2?=?"C:/Users/liqiang/Desktop/圖片/qlq2.jpeg"; ????????//?給圖片添加水印 ????????WaterMarkUtils.markImageByIcon(iconPath,?srcImgPath,?targerPath); ????????//?給圖片添加水印,水印旋轉(zhuǎn)-45 ????????WaterMarkUtils.markImageByIcon(iconPath,?srcImgPath,?targerPath2,?-45); ????} ????/** ?????*?給圖片添加水印 ?????*? ?????*?@param?iconPath ?????*????????????水印圖片路徑 ?????*?@param?srcImgPath ?????*????????????源圖片路徑 ?????*?@param?targerPath ?????*????????????目標(biāo)圖片路徑 ?????*/ ????public?static?void?markImageByIcon(String?iconPath,?String?srcImgPath,?String?targerPath)?{ ????????markImageByIcon(iconPath,?srcImgPath,?targerPath,?null); ????} ????/** ?????*?給圖片添加水印、可設(shè)置水印圖片旋轉(zhuǎn)角度 ?????*? ?????*?@param?iconPath ?????*????????????水印圖片路徑 ?????*?@param?srcImgPath ?????*????????????源圖片路徑 ?????*?@param?targerPath ?????*????????????目標(biāo)圖片路徑 ?????*?@param?degree ?????*????????????水印圖片旋轉(zhuǎn)角度 ?????*/ ????public?static?void?markImageByIcon(String?iconPath,?String?srcImgPath,?String?targerPath,?Integer?degree)?{ ????????OutputStream?os?=?null; ????????try?{ ????????????Image?srcImg?=?ImageIO.read(new?File(srcImgPath)); ????????????BufferedImage?buffImg?=?new?BufferedImage(srcImg.getWidth(null),?srcImg.getHeight(null), ????????????????????BufferedImage.TYPE_INT_RGB); ????????????//?得到畫筆對(duì)象 ????????????//?Graphics?g=?buffImg.getGraphics(); ????????????Graphics2D?g?=?buffImg.createGraphics(); ????????????//?設(shè)置對(duì)線段的鋸齒狀邊緣處理 ????????????g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,?RenderingHints.VALUE_INTERPOLATION_BILINEAR); ????????????g.drawImage(srcImg.getScaledInstance(srcImg.getWidth(null),?srcImg.getHeight(null),?Image.SCALE_SMOOTH),?0, ????????????????????0,?null); ????????????if?(null?!=?degree)?{ ????????????????//?設(shè)置水印旋轉(zhuǎn) ????????????????g.rotate(Math.toRadians(degree),?(double)?buffImg.getWidth()?/?2,?(double)?buffImg.getHeight()?/?2); ????????????} ????????????//?水印圖象的路徑?水印一般為gif或者png的,這樣可設(shè)置透明度 ????????????ImageIcon?imgIcon?=?new?ImageIcon(iconPath); ????????????//?得到Image對(duì)象。 ????????????Image?img?=?imgIcon.getImage(); ????????????float?alpha?=?0.5f;?//?透明度 ????????????g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,?alpha)); ????????????//?表示水印圖片的位置 ????????????g.drawImage(img,?150,?300,?null); ????????????g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER)); ????????????g.dispose(); ????????????os?=?new?FileOutputStream(targerPath); ????????????//?生成圖片 ????????????ImageIO.write(buffImg,?"JPG",?os); ????????????System.out.println("圖片完成添加Icon印章。。。。。。"); ????????}?catch?(Exception?e)?{ ????????????e.printStackTrace(); ????????}?finally?{ ????????????try?{ ????????????????if?(null?!=?os) ????????????????????os.close(); ????????????}?catch?(Exception?e)?{ ????????????????e.printStackTrace(); ????????????} ????????} ????} }
Effect display:
(Free video tutorial: java video tutorial)
------------------------ -----PDF watermark (itext add watermark)-------------------------------
At the same time here Add text watermark and picture watermark to PDF (add a text watermark and picture watermark to each page)
Dependent package:
<dependencies> ????????<dependency> ????????????<groupid>com.lowagie</groupid> ????????????<artifactid>itextasian</artifactid> ????????????<version>1.0</version> ????????</dependency> ????????<dependency> ????????????<groupid>com.lowagie</groupid> ????????????<artifactid>itext</artifactid> ????????????<version>2.1.7</version> ????????</dependency> ????</dependencies>
Specific code:
import?java.awt.Color; import?java.io.BufferedOutputStream; import?java.io.File; import?java.io.FileOutputStream; import?java.io.IOException; import?java.text.SimpleDateFormat; import?java.util.Calendar; import?com.lowagie.text.DocumentException; import?com.lowagie.text.Element; import?com.lowagie.text.Image; import?com.lowagie.text.pdf.BaseFont; import?com.lowagie.text.pdf.PdfContentByte; import?com.lowagie.text.pdf.PdfGState; import?com.lowagie.text.pdf.PdfReader; import?com.lowagie.text.pdf.PdfStamper; public?class?TestWaterPrint?{ ????public?static?void?main(String[]?args)?throws?DocumentException,?IOException?{ ????????//?要輸出的pdf文件 ????????BufferedOutputStream?bos?=?new?BufferedOutputStream(new?FileOutputStream(new?File("E:/abc.pdf"))); ????????Calendar?cal?=?Calendar.getInstance(); ????????SimpleDateFormat?format?=?new?SimpleDateFormat("yyyy-MM-dd?hh:mm:ss"); ????????//?將pdf文件先加水印然后輸出 ????????setWatermark(bos,?"G:/1.pdf",?format.format(cal.getTime())?+?"??下載使用人:"?+?"測(cè)試user",?16); ????} ????/** ?????*? ?????*?@param?bos輸出文件的位置 ?????*?@param?input ?????*????????????原PDF位置 ?????*?@param?waterMarkName ?????*????????????頁腳添加水印 ?????*?@param?permission ?????*????????????權(quán)限碼 ?????*?@throws?DocumentException ?????*?@throws?IOException ?????*/ ????public?static?void?setWatermark(BufferedOutputStream?bos,?String?input,?String?waterMarkName,?int?permission) ????????????throws?DocumentException,?IOException?{ ????????PdfReader?reader?=?new?PdfReader(input); ????????PdfStamper?stamper?=?new?PdfStamper(reader,?bos); ????????int?total?=?reader.getNumberOfPages()?+?1; ????????PdfContentByte?content; ????????BaseFont?base?=?BaseFont.createFont("STSong-Light",?"UniGB-UCS2-H",?BaseFont.EMBEDDED); ????????PdfGState?gs?=?new?PdfGState(); ????????for?(int?i?=?1;?i?<p>Effect display: </p><p><img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/image/584/251/170/1615519483789827.png" class="lazy" title="1615519483789827.png" alt="Java implements adding image watermarks and text watermarks"></p><p>Supplement: About the usage of fonts</p><p>1. Use the fonts in iTextAsian.jar </p><pre class="brush:php;toolbar:false">BaseFont.createFont("STSong-Light",?"UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);
2. Use Windows system font
BaseFont.createFont("C:/WINDOWS/Fonts/SIMYOU.TTF",?BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);
3. Use resource fonts (ClassPath), that is, copy the ttf font to the src directory
BaseFont.createFont("/SIMYOU.TTF",?BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);
. The three methods have been personally tested and effective, and use The fonts that come with itext are enough and can handle Chinese correctly.
Additional information: Regarding obtaining the height and width of the PDF page and then dynamically positioning it, for example, implementing tiled watermarks based on the page width:
package?cn.xm.exam.test; import?java.awt.FontMetrics; import?java.io.BufferedOutputStream; import?java.io.File; import?java.io.FileOutputStream; import?java.io.IOException; import?javax.swing.JLabel; import?com.itextpdf.text.DocumentException; import?com.itextpdf.text.Element; import?com.itextpdf.text.Rectangle; import?com.itextpdf.text.pdf.BaseFont; import?com.itextpdf.text.pdf.PdfContentByte; import?com.itextpdf.text.pdf.PdfGState; import?com.itextpdf.text.pdf.PdfReader; import?com.itextpdf.text.pdf.PdfStamper; public?class?TestWaterPrint?{ ????public?static?void?main(String[]?args)?throws?DocumentException,?IOException?{ ????????//?要輸出的pdf文件 ????????BufferedOutputStream?bos?=?new?BufferedOutputStream(new?FileOutputStream(new?File("F:/test1.pdf"))); ????????//?將pdf文件先加水印然后輸出 ????????setWatermark(bos,?"F:/test.pdf",?"測(cè)試user"); ????} ????/** ?????*? ?????*?@param?bos輸出文件的位置 ?????*?@param?input ?????*????????????原PDF位置 ?????*?@param?waterMarkName ?????*????????????頁腳添加水印 ?????*?@throws?DocumentException ?????*?@throws?IOException ?????*/ ????public?static?void?setWatermark(BufferedOutputStream?bos,?String?input,?String?waterMarkName) ????????????throws?DocumentException,?IOException?{ ????????PdfReader?reader?=?new?PdfReader(input); ????????PdfStamper?stamper?=?new?PdfStamper(reader,?bos); ????????//?獲取總頁數(shù)?+1,?下面從1開始遍歷 ????????int?total?=?reader.getNumberOfPages()?+?1; ????????//?使用classpath下面的字體庫 ????????BaseFont?base?=?null; ????????try?{ ????????????base?=?BaseFont.createFont("/calibri.ttf",?BaseFont.IDENTITY_H,?BaseFont.NOT_EMBEDDED); ????????}?catch?(Exception?e)?{ ????????????//?日志處理 ????????????e.printStackTrace(); ????????} ????????//?間隔 ????????int?interval?=?-5; ????????//?獲取水印文字的高度和寬度 ????????int?textH?=?0,?textW?=?0; ????????JLabel?label?=?new?JLabel(); ????????label.setText(waterMarkName); ????????FontMetrics?metrics?=?label.getFontMetrics(label.getFont()); ????????textH?=?metrics.getHeight(); ????????textW?=?metrics.stringWidth(label.getText()); ????????System.out.println("textH:?"?+?textH); ????????System.out.println("textW:?"?+?textW); ????????//?設(shè)置水印透明度 ????????PdfGState?gs?=?new?PdfGState(); ????????gs.setFillOpacity(0.4f); ????????gs.setStrokeOpacity(0.4f); ????????Rectangle?pageSizeWithRotation?=?null; ????????PdfContentByte?content?=?null; ????????for?(int?i?=?1;?i?<p>Result display: </p><p><img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/image/266/263/910/1615519548460168.png" class="lazy" title="1615519548460168.png" alt="Java implements adding image watermarks and text watermarks"></p><p>Supplementary information: Regarding itext adding italic font watermark</p><p>The above uses BaseFont and cannot add styles. Font can add styles, but the setFontAndSize method does not accept the Font parameter. So we can only work around it: </p><p>For example: generate an oblique watermark in the lower right corner of each page</p><pre class="brush:php;toolbar:false">package?cn.xm.exam.test; import?java.io.BufferedOutputStream; import?java.io.File; import?java.io.FileOutputStream; import?java.io.IOException; import?com.itextpdf.text.DocumentException; import?com.itextpdf.text.Rectangle; import?com.itextpdf.text.pdf.BaseFont; import?com.itextpdf.text.pdf.PdfContentByte; import?com.itextpdf.text.pdf.PdfGState; import?com.itextpdf.text.pdf.PdfReader; import?com.itextpdf.text.pdf.PdfStamper; public?class?TestWaterPrint?{ ????public?static?void?main(String[]?args)?throws?DocumentException,?IOException?{ ????????//?要輸出的pdf文件 ????????BufferedOutputStream?bos?=?new?BufferedOutputStream(new?FileOutputStream(new?File("F:/test2.pdf"))); ????????//?將pdf文件先加水印然后輸出 ????????setWatermark(bos,?"F:/test.pdf",?"測(cè)試user123456789"); ????} ????/** ?????*? ?????*?@param?bos輸出文件的位置 ?????*?@param?input ?????*????????????原PDF位置 ?????*?@param?waterMarkName ?????*????????????頁腳添加水印 ?????*?@throws?DocumentException ?????*?@throws?IOException ?????*/ ????public?static?void?setWatermark(BufferedOutputStream?bos,?String?input,?String?waterMarkName) ????????????throws?DocumentException,?IOException?{ ????????PdfReader?reader?=?new?PdfReader(input); ????????PdfStamper?stamper?=?new?PdfStamper(reader,?bos); ????????//?獲取總頁數(shù)?+1,?下面從1開始遍歷 ????????int?total?=?reader.getNumberOfPages()?+?1; ????????//?使用classpath下面的字體庫 ????????BaseFont?base?=?null; ????????try?{ ????????????base?=?BaseFont.createFont("/calibri.ttf",?BaseFont.IDENTITY_H,?BaseFont.NOT_EMBEDDED); ????????}?catch?(Exception?e)?{ ????????????//?日志處理 ????????????e.printStackTrace(); ????????} ????????//?設(shè)置水印透明度 ????????PdfGState?gs?=?new?PdfGState(); ????????gs.setFillOpacity(0.4f); ????????gs.setStrokeOpacity(0.4f); ????????PdfContentByte?content?=?null; ????????for?(int?i?=?1;?i?<p>Result display:</p><p><img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/image/815/871/608/1615519581569493.png" class="lazy" title="1615519581569493.png" alt="Java implements adding image watermarks and text watermarks"></p><p>Related recommendations: <a href="http://m.miracleart.cn/java/guide/" target="_blank">java introductory tutorial</a></p>
The above is the detailed content of Java implements adding image watermarks and text watermarks. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Singleton design pattern in Java ensures that a class has only one instance and provides a global access point through private constructors and static methods, which is suitable for controlling access to shared resources. Implementation methods include: 1. Lazy loading, that is, the instance is created only when the first request is requested, which is suitable for situations where resource consumption is high and not necessarily required; 2. Thread-safe processing, ensuring that only one instance is created in a multi-threaded environment through synchronization methods or double check locking, and reducing performance impact; 3. Hungry loading, which directly initializes the instance during class loading, is suitable for lightweight objects or scenarios that can be initialized in advance; 4. Enumeration implementation, using Java enumeration to naturally support serialization, thread safety and prevent reflective attacks, is a recommended concise and reliable method. Different implementation methods can be selected according to specific needs

Analyzing Java heap dumps is a key means to troubleshoot memory problems, especially for identifying memory leaks and performance bottlenecks. 1. Use EclipseMAT or VisualVM to open the .hprof file. MAT provides Histogram and DominatorTree views to display the object distribution from different angles; 2. sort in Histogram by number of instances or space occupied to find classes with abnormally large or large size, such as byte[], char[] or business classes; 3. View the reference chain through "ListObjects>withincoming/outgoingreferences" to determine whether it is accidentally held; 4. Use "Pathto

Optional can clearly express intentions and reduce code noise for null judgments. 1. Optional.ofNullable is a common way to deal with null objects. For example, when taking values ??from maps, orElse can be used to provide default values, so that the logic is clearer and concise; 2. Use chain calls maps to achieve nested values ??to safely avoid NPE, and automatically terminate if any link is null and return the default value; 3. Filter can be used for conditional filtering, and subsequent operations will continue to be performed only if the conditions are met, otherwise it will jump directly to orElse, which is suitable for lightweight business judgment; 4. It is not recommended to overuse Optional, such as basic types or simple logic, which will increase complexity, and some scenarios will directly return to nu.

ThreadLocal is used in Java to create thread-private variables, each thread has an independent copy to avoid concurrency problems. It stores values ??through ThreadLocalMap inside the thread. Pay attention to timely cleaning when using it to prevent memory leakage. Common uses include user session management, database connections, transaction context, and log tracking. Best practices include: 1. Call remove() to clean up after use; 2. Avoid overuse; 3. InheritableThreadLocal is required for child thread inheritance; 4. Do not store large objects. The initial value can be set through initialValue() or withInitial(), and the initialization is delayed until the first get() call.

The core workaround for encountering java.io.NotSerializableException is to ensure that all classes that need to be serialized implement the Serializable interface and check the serialization support of nested objects. 1. Add implementsSerializable to the main class; 2. Ensure that the corresponding classes of custom fields in the class also implement Serializable; 3. Use transient to mark fields that do not need to be serialized; 4. Check the non-serialized types in collections or nested objects; 5. Check which class does not implement the interface; 6. Consider replacement design for classes that cannot be modified, such as saving key data or using serializable intermediate structures; 7. Consider modifying

There are three common methods to traverse Map in Java: 1. Use entrySet to obtain keys and values at the same time, which is suitable for most scenarios; 2. Use keySet or values to traverse keys or values respectively; 3. Use Java8's forEach to simplify the code structure. entrySet returns a Set set containing all key-value pairs, and each loop gets the Map.Entry object, suitable for frequent access to keys and values; if only keys or values are required, you can call keySet() or values() respectively, or you can get the value through map.get(key) when traversing the keys; Java 8 can use forEach((key,value)->

Dynamic web crawling can be achieved through an analysis interface or a simulated browser. 1. Use browser developer tools to view XHR/Fetch requests in the Network, find the interface that returns JSON data, and use requests to get it; 2. If the page is rendered by the front-end framework and has no independent interface, you can start the browser with Selenium and wait for the elements to be loaded and extracted; 3. In the face of the anti-crawling mechanism, headers should be added, frequency control, proxy IP should be used, and verification codes or JS rendering detection should be carried out according to the situation. Mastering these methods can effectively deal with most dynamic web crawling scenarios.

In Java, Comparable is used to define default sorting rules internally, and Comparator is used to define multiple sorting logic externally. 1.Comparable is an interface implemented by the class itself. It defines the natural order by rewriting the compareTo() method. It is suitable for classes with fixed and most commonly used sorting methods, such as String or Integer. 2. Comparator is an externally defined functional interface, implemented through the compare() method, suitable for situations where multiple sorting methods are required for the same class, the class source code cannot be modified, or the sorting logic is often changed. The difference between the two is that Comparable can only define a sorting logic and needs to modify the class itself, while Compar
