search
HomeJavajavaTutorialExample analysis of how to add watermark to pictures in Java

Watermark development is a relatively common function in web development, and the implemented code is very simple. This article mainly introduces JAVA image watermark development cases, which has certain reference value. Interested friends can refer to it

Written at the front

Last week I spent a week piecemeal researching the development of watermarks, and now I finally wrote an entry-level Demo and took notes. Also share it for everyone’s reference.

Demo is built on the file import and export (POI method) framework of the JAVA practical case I wrote last time, based on Spring+SpringMVC. Please correct me if there are any mistakes.

Brief introduction

Watermark development is a common function in web development. The implemented code is very simple. I will also follow the specific implementation steps. Detailed description based on code. In fact, based on my personal understanding, I divide the types and development processes of watermarks into the following categories.

Type of watermark:

Single text watermark
Single picture watermark
Multiple text watermark
Multiple picture watermark

Watermark development process:

  • ##Create image cache object

  • Create a Java drawing tool object

  • Use the drawing tool object to draw the original image to the cached image object

  • Use the drawing tool object to draw the Draw watermark (text/picture) to cached image

  • Create image encoding tool class

  • Use image encoding tool class to output cached image to target File


Rendering:

Upload page:

Original Picture:

Single text watermark:

Single picture watermark:

Multiple text watermarks:

##Multiple picture watermarks:

Single text watermark development

The so-called text watermark is to add a text watermark to a picture. Our main process is to decode the corresponding image through the

ImageIO

tool class, then create the BufferImage object, and create the Graphics2D object through the BufferImage object , and then draw the original image to the BufferImage object through the Graphics2D object. Then, we can also use the Graphics2D object to set watermark-related information, such as watermark content, font size, font style, etc. What needs to be explained here is that we need to calculate the width of the watermark text. The Chinese length is the text width, and the English length is one-half of the text width. For details, please refer to the relevant content in my source code.

 //计算水印文本长度
 //1、中文长度即文本长度 2、英文长度为文本长度二分之一
 public int getTextLength(String text){
  //水印文字长度
  int length = text.length();

  for (int i = 0; i < text.length(); i++) {
   String s =String.valueOf(text.charAt(i));
   if (s.getBytes().length>1) {
    length++;
   }
  }
  length = length%2==0?length/2:length/2+1;
  return length;
 }

//添加单条文字水印方法
public String textWaterMark(MultipartFile myFile,String imageFileName) {
InputStream is =null;
OutputStream os =null;
int X = 636;
int Y = 700;

  try {
   //使用ImageIO解码图片
   Image image = ImageIO.read(myFile.getInputStream());
   //计算原始图片宽度长度
   int width = image.getWidth(null);
   int height = image.getHeight(null);
   //创建图片缓存对象
   BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); 
   //创建java绘图工具对象
   Graphics2D graphics2d = bufferedImage.createGraphics();
   //参数主要是,原图,坐标,宽高
   graphics2d.drawImage(image, 0, 0, width, height, null);
   graphics2d.setFont(new Font(FONT_NAME, FONT_STYLE, FONT_SIZE));
   graphics2d.setColor(FONT_COLOR);

   //使用绘图工具将水印绘制到图片上
   //计算文字水印宽高值
   int waterWidth = FONT_SIZE*getTextLength(MARK_TEXT);
   int waterHeight = FONT_SIZE;
   //计算水印与原图高宽差
   int widthDiff = width-waterWidth;
   int heightDiff = height-waterHeight;
   //水印坐标设置
   if (X > widthDiff) {
    X = widthDiff;
   }
   if (Y > heightDiff) {
    Y = heightDiff;
   }
   //水印透明设置
   graphics2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, ALPHA));
   //纵坐标在下方,不增加字体高度会靠上
   graphics2d.drawString(MARK_TEXT, X, Y+FONT_SIZE);

   graphics2d.dispose();
   os = new FileOutputStream(UPLOAD_PATH+"/"+imageFileName);
   //创建图像编码工具类
   JPEGImageEncoder en = JPEGCodec.createJPEGEncoder(os);
   //使用图像编码工具类,输出缓存图像到目标文件
   en.encode(bufferedImage);
   if(is!=null){  
    is.close();
   }
   if(os!=null){
    os.close();
   }
  } catch (IOException e) {
   e.printStackTrace();
  }
  return "success";
 }

Single picture watermark development

Single picture watermark and single text above The code flow is roughly the same, only the differences are explained here.

First we need to get the path of the watermark image, then create the watermark file object, and also decode the watermark image through the ImageIO tool class. In the meantime, we do not need to calculate the length and width of the text, because the length and width of a single text is our watermark image. length and width.


   //水印图片路径
   //水印坐标设置
   String logoPath = "/img/logo.png";
   String realPath = request.getSession().getServletContext().getRealPath(logoPath);
   File logo = new File(realPath);
   Image imageLogo = ImageIO.read(logo);
   int widthLogo = imageLogo.getWidth(null);
   int heightLogo = imageLogo.getHeight(null);
   int widthDiff = width-widthLogo;
   int heightDiff = height-heightLogo;
   //水印坐标设置
   if (X > widthDiff) {
    X = widthDiff;
   }
   if (Y > heightDiff) {
    Y = heightDiff;
   }
   //水印透明设置
   graphics2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, ALPHA));
   graphics2d.drawImage(imageLogo, X, Y, null);

Multi-text watermark development

In fact, multi-text watermark development is similar to single text. The main difference is that we The BufferImage object needs to be rotated. Because drawing watermarks does not support rotating watermarks, we need to rotate and draw the original image, and then through loops, we can draw a text watermark on the original image multiple times.

 //旋转原图,注意旋转角度为弧度制。后面两个参数为旋转的坐标中心
   graphics2d.rotate(Math.toRadians(30), bufferedImage.getWidth()/2, bufferedImage.getHeight()/2);

   int x = -width/2;
   int y = -height/2;

   while(x < width*1.5){
    y = -height/2;
    while(y < height*1.5){
     graphics2d.drawString(MARK_TEXT, x, y);
     y+=waterHeight+100;
    }
    x+=waterWidth+100;
   }

Multi-picture watermark development

Same as above, multi-picture watermarking needs to read the watermark picture first, and then apply the watermark Set the transparency, rotate the original image, and then through looping, we can draw an image watermark on the original image multiple times.

 //水印图片路径
   String logoPath = "/img/logo.png";
   String realPath = request.getSession().getServletContext().getRealPath(logoPath);
   File logo = new File(realPath);
   Image imageLogo = ImageIO.read(logo);
   int widthLogo = imageLogo.getWidth(null);
   int heightLogo = imageLogo.getHeight(null);
   
   //水印透明设置
   graphics2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, ALPHA));
   
   graphics2d.rotate(Math.toRadians(30), bufferedImage.getWidth()/2, bufferedImage.getHeight()/2);
   
   int x = -width/2;
   int y = -height/2;

   while(x < width*1.5){
    y = -height/2;
    while(y < height*1.5){
     graphics2d.drawImage(imageLogo, x, y, null);
     y+=heightLogo+100;
    }
    x+=widthLogo+100;
   }

Complete code for business class:


import java.awt.AlphaComposite;
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 java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.allan.service.WaterMarkService;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
@Service
public class WaterMarkServiceImpl implements WaterMarkService{
 //定义上传的文件夹
 private static final String UPLOAD_PATH = "E:/save";
 //定义水印文字样式
 private static final String MARK_TEXT = "小卖铺的老爷爷";
 private static final String FONT_NAME = "微软雅黑";
 private static final int FONT_STYLE = Font.BOLD;
 private static final int FONT_SIZE = 60;
 private static final Color FONT_COLOR = Color.black;


 private static final float ALPHA = 0.3F;


 //1、上传图片
 public String uploadImage(MultipartFile myFile,String imageFileName) {
 InputStream is =null;
 OutputStream os =null;
 try{
  is = myFile.getInputStream();
  os = new FileOutputStream(UPLOAD_PATH+"/"+imageFileName);
  byte[] buffer =new byte[1024];
  int len = 0;

  while ((len=is.read(buffer))>0){
  os.write(buffer);
  }

 }catch(Exception e){
  e.printStackTrace();
 }finally{
  if(is!=null){
  try {
   is.close();
  } catch (IOException e) {

   e.printStackTrace();
  }
  }
  if(os!=null){
  try {
   os.close();
  } catch (IOException e2) {
   e2.printStackTrace();
  }
  }
 }

 return "success";

 }
 //添加单条文字水印
 public String textWaterMark(MultipartFile myFile,String imageFileName) {
 InputStream is =null;
 OutputStream os =null;
 int X = 636;
 int Y = 700;

 try {
  Image image = ImageIO.read(myFile.getInputStream());
  //计算原始图片宽度长度
  int width = image.getWidth(null);
  int height = image.getHeight(null);
  //创建图片缓存对象
  BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); 
  //创建java绘图工具对象
  Graphics2D graphics2d = bufferedImage.createGraphics();
  //参数主要是,原图,坐标,宽高
  graphics2d.drawImage(image, 0, 0, width, height, null);
  graphics2d.setFont(new Font(FONT_NAME, FONT_STYLE, FONT_SIZE));
  graphics2d.setColor(FONT_COLOR);

  //使用绘图工具将水印绘制到图片上
  //计算文字水印宽高值
  int waterWidth = FONT_SIZE*getTextLength(MARK_TEXT);
  int waterHeight = FONT_SIZE;
  //计算水印与原图高宽差
  int widthDiff = width-waterWidth;
  int heightDiff = height-waterHeight;
  //水印坐标设置
  if (X > widthDiff) {
  X = widthDiff;
  }
  if (Y > heightDiff) {
  Y = heightDiff;
  }
  //水印透明设置
  graphics2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, ALPHA));
  graphics2d.drawString(MARK_TEXT, X, Y+FONT_SIZE);

  graphics2d.dispose();
  os = new FileOutputStream(UPLOAD_PATH+"/"+imageFileName);
  //创建图像编码工具类
  JPEGImageEncoder en = JPEGCodec.createJPEGEncoder(os);
  //使用图像编码工具类,输出缓存图像到目标文件
  en.encode(bufferedImage);
  if(is!=null){ 
  is.close();
  }
  if(os!=null){
  os.close();
  }
 } catch (IOException e) {
  e.printStackTrace();
 }
 return "success";
 }

 //添加单图片水印
 public String imageWaterMark(MultipartFile myFile,String imageFileName,HttpServletRequest request) {
 InputStream is =null;
 OutputStream os =null;
 int X = 636;
 int Y = 763;

 try {
  Image image = ImageIO.read(myFile.getInputStream());
  //计算原始图片宽度长度
  int width = image.getWidth(null);
  int height = image.getHeight(null);
  //创建图片缓存对象
  BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); 
  //创建java绘图工具对象
  Graphics2D graphics2d = bufferedImage.createGraphics();
  //参数主要是,原图,坐标,宽高
  graphics2d.drawImage(image, 0, 0, width, height, null);
  graphics2d.setFont(new Font(FONT_NAME, FONT_STYLE, FONT_SIZE));
  graphics2d.setColor(FONT_COLOR);

  //水印图片路径
  String logoPath = "/img/logo.png";
  String realPath = request.getSession().getServletContext().getRealPath(logoPath);
  File logo = new File(realPath);
  Image imageLogo = ImageIO.read(logo);
  int widthLogo = imageLogo.getWidth(null);
  int heightLogo = imageLogo.getHeight(null);
  int widthDiff = width-widthLogo;
  int heightDiff = height-heightLogo;
  //水印坐标设置
  if (X > widthDiff) {
  X = widthDiff;
  }
  if (Y > heightDiff) {
  Y = heightDiff;
  }
  //水印透明设置
  graphics2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, ALPHA));
  graphics2d.drawImage(imageLogo, X, Y, null);

  graphics2d.dispose();
  os = new FileOutputStream(UPLOAD_PATH+"/"+imageFileName);
  //创建图像编码工具类
  JPEGImageEncoder en = JPEGCodec.createJPEGEncoder(os);
  //使用图像编码工具类,输出缓存图像到目标文件
  en.encode(bufferedImage);
  if(is!=null){ 
  is.close();
  }
  if(os!=null){
  os.close();
  }
 } catch (IOException e) {
  e.printStackTrace();
 }
 return "success";
 }
 //添加多条文字水印
 public String moreTextWaterMark(MultipartFile myFile,String imageFileName) {
 InputStream is =null;
 OutputStream os =null;
 int X = 636;
 int Y = 763;

 try {
  Image image = ImageIO.read(myFile.getInputStream());
  //计算原始图片宽度长度
  int width = image.getWidth(null);
  int height = image.getHeight(null);
  //创建图片缓存对象
  BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); 
  //创建java绘图工具对象
  Graphics2D graphics2d = bufferedImage.createGraphics();
  //参数主要是,原图,坐标,宽高
  graphics2d.drawImage(image, 0, 0, width, height, null);
  graphics2d.setFont(new Font(FONT_NAME, FONT_STYLE, FONT_SIZE));
  graphics2d.setColor(FONT_COLOR);

  //使用绘图工具将水印绘制到图片上
  //计算文字水印宽高值
  int waterWidth = FONT_SIZE*getTextLength(MARK_TEXT);
  int waterHeight = FONT_SIZE;

  //水印透明设置
  graphics2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, ALPHA));
  graphics2d.rotate(Math.toRadians(30), bufferedImage.getWidth()/2, bufferedImage.getHeight()/2);

  int x = -width/2;
  int y = -height/2;

  while(x < width*1.5){
  y = -height/2;
  while(y < height*1.5){
   graphics2d.drawString(MARK_TEXT, x, y);
   y+=waterHeight+100;
  }
  x+=waterWidth+100;
  }
  graphics2d.dispose();

  os = new FileOutputStream(UPLOAD_PATH+"/"+imageFileName);
  //创建图像编码工具类
  JPEGImageEncoder en = JPEGCodec.createJPEGEncoder(os);
  //使用图像编码工具类,输出缓存图像到目标文件
  en.encode(bufferedImage);
  if(is!=null){ 
  is.close();
  }
  if(os!=null){
  os.close();
  }
 } catch (IOException e) {
  e.printStackTrace();
 }
 return "success";
 }

 //多图片水印
 public String moreImageWaterMark(MultipartFile myFile,String imageFileName,HttpServletRequest request) {
 InputStream is =null;
 OutputStream os =null;
 int X = 636;
 int Y = 763;

 try {
  Image image = ImageIO.read(myFile.getInputStream());
  //计算原始图片宽度长度
  int width = image.getWidth(null);
  int height = image.getHeight(null);
  //创建图片缓存对象
  BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); 
  //创建java绘图工具对象
  Graphics2D graphics2d = bufferedImage.createGraphics();
  //参数主要是,原图,坐标,宽高
  graphics2d.drawImage(image, 0, 0, width, height, null);
  graphics2d.setFont(new Font(FONT_NAME, FONT_STYLE, FONT_SIZE));
  graphics2d.setColor(FONT_COLOR);

  //水印图片路径
  String logoPath = "/img/logo.png";
  String realPath = request.getSession().getServletContext().getRealPath(logoPath);
  File logo = new File(realPath);
  Image imageLogo = ImageIO.read(logo);
  int widthLogo = imageLogo.getWidth(null);
  int heightLogo = imageLogo.getHeight(null);
  
  //水印透明设置
  graphics2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, ALPHA));
  
  graphics2d.rotate(Math.toRadians(30), bufferedImage.getWidth()/2, bufferedImage.getHeight()/2);
  
  int x = -width/2;
  int y = -height/2;

  while(x < width*1.5){
  y = -height/2;
  while(y < height*1.5){
   graphics2d.drawImage(imageLogo, x, y, null);
   y+=heightLogo+100;
  }
  x+=widthLogo+100;
  }
  graphics2d.dispose();
  os = new FileOutputStream(UPLOAD_PATH+"/"+imageFileName);
  //创建图像编码工具类
  JPEGImageEncoder en = JPEGCodec.createJPEGEncoder(os);
  //使用图像编码工具类,输出缓存图像到目标文件
  en.encode(bufferedImage);
  if(is!=null){ 
  is.close();
  }
  if(os!=null){
  os.close();
  }
 } catch (IOException e) {
  e.printStackTrace();
 }
 return "success";
 }

 //计算水印文本长度
 //1、中文长度即文本长度 2、英文长度为文本长度二分之一
 public int getTextLength(String text){
 //水印文字长度
 int length = text.length();

 for (int i = 0; i < text.length(); i++) {
  String s =String.valueOf(text.charAt(i));
  if (s.getBytes().length>1) {
  length++;
  }
 }
 length = length%2==0?length/2:length/2+1;
 return length;
 }
}

Finally, this Demo is based on It is written based on the file import and export framework. There are some other Demo codes in the source code. The main classes used are WaterMarkController.java, WaterMarkService.java, WaterMarkServiceImpl.java, because I hardcoded the code into the E:/save file. folder, if you want to run it, please create a new folder first, or change it to another folder.

The above is the detailed content of Example analysis of how to add watermark to pictures in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
What are the advantages of using bytecode over native code for platform independence?What are the advantages of using bytecode over native code for platform independence?Apr 30, 2025 am 12:24 AM

Bytecodeachievesplatformindependencebybeingexecutedbyavirtualmachine(VM),allowingcodetorunonanyplatformwiththeappropriateVM.Forexample,JavabytecodecanrunonanydevicewithaJVM,enabling"writeonce,runanywhere"functionality.Whilebytecodeoffersenh

Is Java truly 100% platform-independent? Why or why not?Is Java truly 100% platform-independent? Why or why not?Apr 30, 2025 am 12:18 AM

Java cannot achieve 100% platform independence, but its platform independence is implemented through JVM and bytecode to ensure that the code runs on different platforms. Specific implementations include: 1. Compilation into bytecode; 2. Interpretation and execution of JVM; 3. Consistency of the standard library. However, JVM implementation differences, operating system and hardware differences, and compatibility of third-party libraries may affect its platform independence.

How does Java's platform independence support code maintainability?How does Java's platform independence support code maintainability?Apr 30, 2025 am 12:15 AM

Java realizes platform independence through "write once, run everywhere" and improves code maintainability: 1. High code reuse and reduces duplicate development; 2. Low maintenance cost, only one modification is required; 3. High team collaboration efficiency is high, convenient for knowledge sharing.

What are the challenges in creating a JVM for a new platform?What are the challenges in creating a JVM for a new platform?Apr 30, 2025 am 12:15 AM

The main challenges facing creating a JVM on a new platform include hardware compatibility, operating system compatibility, and performance optimization. 1. Hardware compatibility: It is necessary to ensure that the JVM can correctly use the processor instruction set of the new platform, such as RISC-V. 2. Operating system compatibility: The JVM needs to correctly call the system API of the new platform, such as Linux. 3. Performance optimization: Performance testing and tuning are required, and the garbage collection strategy is adjusted to adapt to the memory characteristics of the new platform.

How does the JavaFX library attempt to address platform inconsistencies in GUI development?How does the JavaFX library attempt to address platform inconsistencies in GUI development?Apr 30, 2025 am 12:01 AM

JavaFXeffectivelyaddressesplatforminconsistenciesinGUIdevelopmentbyusingaplatform-agnosticscenegraphandCSSstyling.1)Itabstractsplatformspecificsthroughascenegraph,ensuringconsistentrenderingacrossWindows,macOS,andLinux.2)CSSstylingallowsforfine-tunin

Explain how the JVM acts as an intermediary between the Java code and the underlying operating system.Explain how the JVM acts as an intermediary between the Java code and the underlying operating system.Apr 29, 2025 am 12:23 AM

JVM works by converting Java code into machine code and managing resources. 1) Class loading: Load the .class file into memory. 2) Runtime data area: manage memory area. 3) Execution engine: interpret or compile execution bytecode. 4) Local method interface: interact with the operating system through JNI.

Explain the role of the Java Virtual Machine (JVM) in Java's platform independence.Explain the role of the Java Virtual Machine (JVM) in Java's platform independence.Apr 29, 2025 am 12:21 AM

JVM enables Java to run across platforms. 1) JVM loads, validates and executes bytecode. 2) JVM's work includes class loading, bytecode verification, interpretation execution and memory management. 3) JVM supports advanced features such as dynamic class loading and reflection.

What steps would you take to ensure a Java application runs correctly on different operating systems?What steps would you take to ensure a Java application runs correctly on different operating systems?Apr 29, 2025 am 12:11 AM

Java applications can run on different operating systems through the following steps: 1) Use File or Paths class to process file paths; 2) Set and obtain environment variables through System.getenv(); 3) Use Maven or Gradle to manage dependencies and test. Java's cross-platform capabilities rely on the JVM's abstraction layer, but still require manual handling of certain operating system-specific features.

See all articles

Hot AI Tools

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.

Undress AI Tool

Undress AI Tool

Undress images for free

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

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools