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); // 根据图片的背景设置水印颜色 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); // 给图片添加水印,水印旋转-45 WaterMarkUtils.markImageByIcon(iconPath, srcImgPath, targerPath2, -45); } /** * 给图片添加水印 * * @param iconPath * 水印图片路径 * @param srcImgPath * 源图片路径 * @param targerPath * 目标图片路径 */ public static void markImageByIcon(String iconPath, String srcImgPath, String targerPath) { markImageByIcon(iconPath, srcImgPath, targerPath, null); } /** * 给图片添加水印、可设置水印图片旋转角度 * * @param iconPath * 水印图片路径 * @param srcImgPath * 源图片路径 * @param targerPath * 目标图片路径 * @param degree * 水印图片旋转角度 */ 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); // 得到画笔对象 // Graphics g= buffImg.getGraphics(); Graphics2D g = buffImg.createGraphics(); // 设置对线段的锯齿状边缘处理 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) { // 设置水印旋转 g.rotate(Math.toRadians(degree), (double) buffImg.getWidth() / 2, (double) buffImg.getHeight() / 2); } // 水印图象的路径 水印一般为gif或者png的,这样可设置透明度 ImageIcon imgIcon = new ImageIcon(iconPath); // 得到Image对象。 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()) + " 下载使用人:" + "测试user", 16); } /** * * @param bos输出文件的位置 * @param input * 原PDF位置 * @param waterMarkName * 页脚添加水印 * @param permission * 权限码 * @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); // 获取总页数 +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); // 设置水印透明度 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); // 获取总页数 +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(); } // 设置水印透明度 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="https://www.php.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

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

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

Undress AI Tool
Undress images for free

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

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.
