亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Home Java Javagetting Started Java implements adding image watermarks and text watermarks

Java implements adding image watermarks and text watermarks

Mar 12, 2021 am 11:34 AM
java picture letter watermark

Java implements adding image watermarks and text watermarks

We 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:

Java implements adding image watermarks and text watermarks

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:

Java implements adding image watermarks and text watermarks

Java implements adding image watermarks and text watermarks

(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())?+?"??下載使用人:"?+?"測試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",?"測試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",?"測試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://ipnx.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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1488
72
VSCode settings.json location VSCode settings.json location Aug 01, 2025 am 06:12 AM

The settings.json file is located in the user-level or workspace-level path and is used to customize VSCode settings. 1. User-level path: Windows is C:\Users\\AppData\Roaming\Code\User\settings.json, macOS is /Users//Library/ApplicationSupport/Code/User/settings.json, Linux is /home//.config/Code/User/settings.json; 2. Workspace-level path: .vscode/settings in the project root directory

How to handle transactions in Java with JDBC? How to handle transactions in Java with JDBC? Aug 02, 2025 pm 12:29 PM

To correctly handle JDBC transactions, you must first turn off the automatic commit mode, then perform multiple operations, and finally commit or rollback according to the results; 1. Call conn.setAutoCommit(false) to start the transaction; 2. Execute multiple SQL operations, such as INSERT and UPDATE; 3. Call conn.commit() if all operations are successful, and call conn.rollback() if an exception occurs to ensure data consistency; at the same time, try-with-resources should be used to manage resources, properly handle exceptions and close connections to avoid connection leakage; in addition, it is recommended to use connection pools and set save points to achieve partial rollback, and keep transactions as short as possible to improve performance.

Mastering Dependency Injection in Java with Spring and Guice Mastering Dependency Injection in Java with Spring and Guice Aug 01, 2025 am 05:53 AM

DependencyInjection(DI)isadesignpatternwhereobjectsreceivedependenciesexternally,promotingloosecouplingandeasiertestingthroughconstructor,setter,orfieldinjection.2.SpringFrameworkusesannotationslike@Component,@Service,and@AutowiredwithJava-basedconfi

python itertools combinations example python itertools combinations example Jul 31, 2025 am 09:53 AM

itertools.combinations is used to generate all non-repetitive combinations (order irrelevant) that selects a specified number of elements from the iterable object. Its usage includes: 1. Select 2 element combinations from the list, such as ('A','B'), ('A','C'), etc., to avoid repeated order; 2. Take 3 character combinations of strings, such as "abc" and "abd", which are suitable for subsequence generation; 3. Find the combinations where the sum of two numbers is equal to the target value, such as 1 5=6, simplify the double loop logic; the difference between combinations and arrangement lies in whether the order is important, combinations regard AB and BA as the same, while permutations are regarded as different;

Troubleshooting Common Java `OutOfMemoryError` Scenarios Troubleshooting Common Java `OutOfMemoryError` Scenarios Jul 31, 2025 am 09:07 AM

java.lang.OutOfMemoryError: Javaheapspace indicates insufficient heap memory, and needs to check the processing of large objects, memory leaks and heap settings, and locate and optimize the code through the heap dump analysis tool; 2. Metaspace errors are common in dynamic class generation or hot deployment due to excessive class metadata, and MaxMetaspaceSize should be restricted and class loading should be optimized; 3. Unabletocreatenewnativethread due to exhausting system thread resources, it is necessary to check the number of threads, use thread pools, and adjust the stack size; 4. GCoverheadlimitexceeded means that GC is frequent but has less recycling, and GC logs should be analyzed and optimized.

python pytest fixture example python pytest fixture example Jul 31, 2025 am 09:35 AM

fixture is a function used to provide preset environment or data for tests. 1. Use the @pytest.fixture decorator to define fixture; 2. Inject fixture in parameter form in the test function; 3. Execute setup before yield, and then teardown; 4. Control scope through scope parameters, such as function, module, etc.; 5. Place the shared fixture in conftest.py to achieve cross-file sharing, thereby improving the maintainability and reusability of tests.

Understanding the Java Virtual Machine (JVM) Internals Understanding the Java Virtual Machine (JVM) Internals Aug 01, 2025 am 06:31 AM

TheJVMenablesJava’s"writeonce,runanywhere"capabilitybyexecutingbytecodethroughfourmaincomponents:1.TheClassLoaderSubsystemloads,links,andinitializes.classfilesusingbootstrap,extension,andapplicationclassloaders,ensuringsecureandlazyclassloa

How to work with Calendar in Java? How to work with Calendar in Java? Aug 02, 2025 am 02:38 AM

Use classes in the java.time package to replace the old Date and Calendar classes; 2. Get the current date and time through LocalDate, LocalDateTime and LocalTime; 3. Create a specific date and time using the of() method; 4. Use the plus/minus method to immutably increase and decrease the time; 5. Use ZonedDateTime and ZoneId to process the time zone; 6. Format and parse date strings through DateTimeFormatter; 7. Use Instant to be compatible with the old date types when necessary; date processing in modern Java should give priority to using java.timeAPI, which provides clear, immutable and linear

See all articles