Example of Java method to add image watermark text watermark and Mosaic to image

  • 2021-01-03 20:53:46
  • OfStack

This paper introduces the method of Java to add image watermark, text watermark and Mosaic. To share for your reference, the details are as follows:

You can create a new Utils class in eclipse and copy the following code into it for direct use. The following method adds a single or multiple watermarks


package com.rzxt.fyx.common.util;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
/**
 *  Add a watermark to an image 
 * @author tgy
 *
 */
public class MarkImageUtils {
  /**
   * @param args
   */
  public static void main(String[] args) {
  String output = "F:/images/";
    String source = "F:/images/6.jpg";  // Source image path 
    String icon = "F:/images/icon2.png"; // Overlay image path 
    String imageName = "mark_image"; // Image name 
    String imageType = "jpg"; // Image type jpg,jpeg,png,gif
    String text = " The watermarking ";
    int size = 4;  // Mosaic size 
    Integer degree = null; // Watermark rotation Angle -45 . null Means no rotation 
    String result = null;
    // Add image watermark to the image 
    result = MarkImageUtils.markImageByMoreIcon(icon,source,output,imageName,imageType,degree);
//    result = MarkImageUtils.markImageBySingleIcon(icon, source, output, imageName, imageType, degree);
//    // Add a text watermark to an image 
//    result = MarkImageUtils.markImageByMoreText(source,output,imageName,imageType,Color.red,text,degree);
//    result = MarkImageUtils.markImageBySingleText(source,output,imageName,imageType,Color.red,text,degree);
//    // Make a Mosaic of the picture 
//    result = MarkImageUtils.markImageByMosaic(source,output,imageName,imageType,size);
    System.out.println(result);
  }
/**
   *  Add multiple image watermarks to different positions of the image, and set the rotation Angle of the watermark image 
   * @param icon  Watermark image path (such as: F:/images/icon.png ) 
   * @param source  Path to image without watermark (for example: F:/images/6.jpg ) 
   * @param output  Watermark image path (such as: F:/images/ ) 
   * @param imageName  Picture name (e.g. : 11111 ) 
   * @param imageType  Picture type (e.g. : jpg ) 
   * @param degree  The watermark image rotation Angle, is null Means no rotation 
   */
  public static String markImageByMoreIcon(String icon,String source,String output,String imageName,String imageType,Integer degree) {
    String result = " Error adding image watermark ";
    try {
    File file = new File(source);
    File ficon = new File(icon);
    if (!file.isFile()) {
      return source + "  not 1 A picture file !";
    }
      // will icon Load into memory 
      Image ic = ImageIO.read(ficon);
      //icon highly 
      int icheight = ic.getHeight(null);
      // Read the source image into memory 
      Image img = ImageIO.read(file);
      // Image width 
      int width = img.getWidth(null);
      // Pictures of high 
      int height = img.getHeight(null);
      BufferedImage bi = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
      // create 1 A specified  BufferedImage  the  Graphics2D  object 
      Graphics2D g = bi.createGraphics();
      //x,y Axis default is from 0 Coordinate began 
      int x = 0;
      int y = 0;
      // The default height between two watermark images is the watermark image 1/3
      int temp = icheight/3;
      int space = 1;
      if(height>=icheight){
      space = height/icheight;
      if(space>=2){
      temp = y = icheight/2;
      if(space==1||space==0){
      x = 0;
      y = 0;
      }
      }
      }else{
      x = 0;
      y = 0;
      }
      // Set jagged edge handling for line segments 
      g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BILINEAR);
      // present 1 The image is converted from image space to user space before drawing 
      g.drawImage(img.getScaledInstance(width,height,Image.SCALE_SMOOTH),0,0,null);
      for(int i=0;i<space;i++){
      if (null != degree) {
        // Set watermark rotation 
        g.rotate(Math.toRadians(degree),(double) bi.getWidth() / 2, (double) bi.getHeight() / 2);
      }
      // The path of the watermark image   The watermark 1 As for the gif or png , so you can set the transparency 
      ImageIcon imgIcon = new ImageIcon(icon);
      // get Image Object. 
      Image con = imgIcon.getImage();
      // Transparency, minimum 0 , the maximum value is 1
      float clarity = 0.6f;
      g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,clarity));
      // Represents the coordinate position of the watermark image (x,y)
      //g.drawImage(con, 300, 220, null);
      g.drawImage(con, x, y, null);
      g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
      y+=(icheight+temp);
      }
      g.dispose();
      File sf = new File(output, imageName+"."+imageType);
    ImageIO.write(bi, imageType, sf); //  Save the picture 
      result = " Add the picture Icon The watermark ";
    } catch (Exception e) {
      e.printStackTrace();
    }
    return result;
  }
/**
   *  Add a single image watermark to the image, can set the watermark image rotation Angle 
   * @param icon  Watermark image path (such as: F:/images/icon.png ) 
   * @param source  Path to image without watermark (for example: F:/images/6.jpg ) 
   * @param output  Watermark image path (such as: F:/images/ ) 
   * @param imageName  Picture name (e.g. : 11111 ) 
   * @param imageType  Picture type (e.g. : jpg ) 
   * @param degree  The watermark image rotation Angle, is null Means no rotation 
   */
  public static String markImageBySingleIcon(String icon,String source,String output,String imageName,String imageType,Integer degree) {
    String result = " Error adding image watermark ";
    try {
    File file = new File(source);
    File ficon = new File(icon);
    if (!file.isFile()) {
      return source + "  not 1 A picture file !";
    }
      // will icon Load into memory 
      Image ic = ImageIO.read(ficon);
      //icon highly 
      int icheight = ic.getHeight(null);
      // Read the source image into memory 
      Image img = ImageIO.read(file);
      // Image width 
      int width = img.getWidth(null);
      // Pictures of high 
      int height = img.getHeight(null);
      BufferedImage bi = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
      // create 1 A specified  BufferedImage  the  Graphics2D  object 
      Graphics2D g = bi.createGraphics();
      //x,y Axis default is from 0 Coordinate began 
      int x = 0;
      int y = (height/2)-(icheight/2);
      // Set jagged edge handling for line segments 
      g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BILINEAR);
      // present 1 The image is converted from image space to user space before drawing 
      g.drawImage(img.getScaledInstance(width,height,Image.SCALE_SMOOTH),0,0,null);
      if (null != degree) {
        // Set watermark rotation 
        g.rotate(Math.toRadians(degree),(double) bi.getWidth() / 2, (double) bi.getHeight() / 2);
      }
      // The path of the watermark image   The watermark 1 As for the gif or png , so you can set the transparency 
      ImageIcon imgIcon = new ImageIcon(icon);
      // get Image Object. 
      Image con = imgIcon.getImage();
      // Transparency, minimum 0 , the maximum value is 1
      float clarity = 0.6f;
      g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,clarity));
      // Represents the coordinate position of the watermark image (x,y)
      //g.drawImage(con, 300, 220, null);
      g.drawImage(con, x, y, null);
      g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
      g.dispose();
      File sf = new File(output, imageName+"."+imageType);
    ImageIO.write(bi, imageType, sf); //  Save the picture 
      result = " Add the picture Icon The watermark ";
    } catch (Exception e) {
      e.printStackTrace();
    }
    return result;
  }
  /**
   *  Add multiple text watermarks to the image and set the rotation Angle of the watermark 
   * @param source  The image path to which the watermark is to be added (for example: F:/images/6.jpg ) 
   * @param outPut  After adding watermark, the image output path (such as: F:/images/ ) 
   * @param imageName  Picture name (e.g. : 11111 ) 
   * @param imageType  Picture type (e.g. : jpg ) 
   * @param color  The color of the watermark 
   * @param word  Watermark text 
   * @param degree  The watermark text rotation Angle, is null Means no rotation 
   */
  public static String markImageByMoreText(String source,String output,String imageName,String imageType,Color color,String word,Integer degree) {
    String result = " Error adding text watermark ";
  try {
      // Read the original image information 
      File file = new File(source);
      if (!file.isFile()) {
      return file + "  not 1 A picture file !";
    }
      Image img = ImageIO.read(file);
      // Image width 
      int width = img.getWidth(null);
      // Pictures of high 
      int height = img.getHeight(null);
      // Text size 
      int size = 50;
      // watermarking 
      BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
      Graphics2D g = bi.createGraphics();
      g.drawImage(img, 0, 0, width, height, null);
      // Sets the watermark font style 
      Font font = new Font(" Song typeface ", Font.PLAIN, size);
      // Set the watermark color according to the background of the image 
      g.setColor(color);
      int x = width/3;
      int y = size;
      int space = height/size;
      for(int i=0;i<space;i++){
      // If the last 1 A coordinate y Axial ratio height High, just quit 
      if((y+size)>height){
      break;
      }
      if (null != degree) {
        // Set watermark rotation 
        g.rotate(Math.toRadians(degree),(double) bi.getWidth() / 2, (double) bi.getHeight() / 2);
      }
      g.setFont(font);
      // The watermark position 
      g.drawString(word, x, y);
      y+=(2*size);
      }
      g.dispose();
      // The output image 
      File sf = new File(output, imageName+"."+imageType);
    ImageIO.write(bi, imageType, sf); //  Save the picture 
      result = " Add the picture Word The watermark ";
    } catch (Exception e) {
      e.printStackTrace();
    }
  return result;
  }
  /**
   *  Add a single text watermark to the image and set the rotation Angle of the watermark 
   * @param source  The image path to which the watermark is to be added (for example: F:/images/6.jpg ) 
   * @param outPut  After adding watermark, the image output path (such as: F:/images/ ) 
   * @param imageName  Picture name (e.g. : 11111 ) 
   * @param imageType  Picture type (e.g. : jpg ) 
   * @param color  The color of the watermark 
   * @param word  Watermark text 
   * @param degree  The watermark text rotation Angle, is null Means no rotation 
   */
  public static String markImageBySingleText(String source,String output,String imageName,String imageType,Color color,String word,Integer degree) {
    String result = " Error adding text watermark ";
  try {
      // Read the original image information 
      File file = new File(source);
      if (!file.isFile()) {
      return file + "  not 1 A picture file !";
    }
      Image img = ImageIO.read(file);
      int width = img.getWidth(null);
      int height = img.getHeight(null);
      // watermarking 
      BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
      Graphics2D g = bi.createGraphics();
      g.drawImage(img, 0, 0, width, height, null);
      // Sets the watermark font style 
      Font font = new Font(" Song typeface ", Font.PLAIN, 50);
      // Set the watermark color according to the background of the image 
      g.setColor(color);
      if (null != degree) {
        // Set watermark rotation 
        g.rotate(Math.toRadians(degree),(double) bi.getWidth() / 2, (double) bi.getHeight() / 2);
      }
      g.setFont(font);
      int x = width/3;
      int y = height/2;
      // The watermark position 
      g.drawString(word, x, y);
      g.dispose();
      // The output image 
      File sf = new File(output, imageName+"."+imageType);
    ImageIO.write(bi, imageType, sf); //  Save the picture 
      result = " Add the picture Word The watermark ";
    } catch (Exception e) {
      e.printStackTrace();
    }
  return result;
  }
  /**
   *  Add mosaics to the picture 
   * @param source  Path of the original picture (such as: F:/images/6.jpg ) 
   * @param output  After the Mosaic, the picture saved path (such as: F:/images/ ) 
   * @param imageName  Picture name (e.g. : 11111 ) 
   * @param imageType  Picture type (e.g. : jpg ) 
   * @param size  The Mosaic size is the width and height of each rectangle 
   * @return
   */
  public static String markImageByMosaic(String source,String output,String imageName,String imageType,int size){
  String result = " Picture Mosaic error ";
  try{
    File file = new File(source);
    if (!file.isFile()) {
      return file + "  not 1 A picture file !";
    }
    BufferedImage img = ImageIO.read(file); //  Read the picture 
    int width = img.getWidth(null); // The original image width 
      int height = img.getHeight(null); // The original image with high 
    BufferedImage bi = new BufferedImage(width,height, BufferedImage.TYPE_INT_RGB);
    // Mosaics are too large or too small 
    if (width < size || height < size) {
      return " The Mosaic lattice is too large ";
    }
    if(size<=0){
     return " The Mosaic lattice is too small ";
    }
    int xcount = 0; //x Number of direction drawing 
    int ycount = 0; //y Number of direction drawing 
    if (width % size == 0) {
      xcount = width / size;
    } else {
      xcount = width / size + 1;
    }
    if (height % size == 0) {
      ycount = height / size;
    } else {
      ycount = height / size + 1;
    }
    int x = 0; //x coordinates 
    int y = 0;
//y coordinates 
    // Paint Mosaic ( Draws a rectangle and fills it with color )
    Graphics2D g = bi.createGraphics();
    for (int i = 0; i < xcount; i++) {
      for (int j = 0; j < ycount; j++) {
        // Mosaic rectangular grid size 
        int mwidth = size;
        int mheight = size;
        if(i==xcount-1){  // Transverse finally 1 One is not 1 a size
          mwidth = width-x;
        }
        if(j == ycount-1){ // Longitudinal finally 1 One is not 1 a size
          mheight = height-y;
        }
        // The rectangle color takes the center pixel RGB value 
        int centerX = x;
        int centerY = y;
        if (mwidth % 2 == 0) {
          centerX += mwidth / 2;
        } else {
          centerX += (mwidth - 1) / 2;
        }
        if (mheight % 2 == 0) {
          centerY += mheight / 2;
        } else {
          centerY += (mheight - 1) / 2;
        }
        Color color = new Color(img.getRGB(centerX, centerY));
        g.setColor(color);
        g.fillRect(x, y, mwidth, mheight);
        y = y + size;//  Under the calculation 1 A rectangular y coordinates 
      }
      y = 0;//  reduction y coordinates 
      x = x + size;//  To calculate x coordinates 
    }
    g.dispose();
    File sf = new File(output, imageName+"."+imageType);
    ImageIO.write(bi, imageType, sf); //  Save the picture 
    result = " Mosaic success ";
  }catch(Exception e){
  e.printStackTrace();
  }
    return result;
  }
}

More java related content interested readers can see the special topics: Java picture operation skills Summary, java Date and time operation skills Summary, Java Operation DOM node skills Summary, Java File and directory operation Skills Summary and Java Data Structure and Algorithm Tutorial.

I hope this article has been helpful in java programming.


Related articles: