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="https://img.php.cn/upload/image/584/251/170/1615519483789827.png" 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="https://img.php.cn/upload/image/266/263/910/1615519548460168.png" 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="https://img.php.cn/upload/image/815/871/608/1615519581569493.png" title="1615519581569493.png" alt="Java implements adding image watermarks and text watermarks"></p><p>Related recommendations: <a href="//m.sbmmt.com/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!