This article describes the Java method of adding image watermarks, text watermarks and mosaics to images. Share it for your reference, as follows:
You can create a new Utils class in eclipse, copy the following code and use it directly, and the following method realizes the addition of 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 the 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"; //Overcover image path String imageName = "mark_image"; //Image name String imageType = "jpg"; //Image type jpg,jpeg,png,gif String text = "Watermarked"; int size = 4; //Mosaic size Integer degree = null; //The watermark rotation angle is -45, null means not to rotate 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 text watermark to the image// result = MarkImageUtils.markImageByMoreText(source,output,imageName,imageType,Color.red,text,degree);// result = MarkImageUtils.markImageBySingleText(source,output,imageName,imageType,Color.red,text,degree);// //Mosaic the image// result = MarkImageUtils.markImageByMosaic(source,output,imageName,imageType,size); System.out.println(result); }/** * Add multiple image watermarks to different locations 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 Image path without watermark (such as: F:/images/6.jpg) * @param output The image path after watermark (such as: F:/images/) * @param imageName Image name (such as: 11111) * @param imageType Image type (such as: jpg) * @param degree The rotation angle of the watermark image, 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 an image file!"; } //Load the icon into memory Image ic = ImageIO.read(ficon); //icon height int iheight = ic.getHeight(null); //Read the source image into memory Image img = ImageIO.read(file); //Image width int width = img.getWidth(null); //Image height int height = img.getHeight(null); BufferedImage bi = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB); //Create a Graphics2D object with a specified BufferedImage Graphics2D g = bi.createGraphics(); //x, the y-axis defaults to start from 0 coordinates int x = 0; int y = 0; //The interval height of the two watermark images is 1/3 of the watermark image int temp = iheight/3; int space = 1; if(height>=iheight){ space = height/iheight; if(space>=2){ temp = y = iheight/2; if(space==1||space==0){ x = 0; y = 0; } } }else{ x = 0; y = 0; } //Set the jagged edge processing of the line segment g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BILINEAR); //Represent an image and convert 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 the watermark rotation g.rotate(Math.toRadians(degree),(double) bi.getWidth() / 2, (double) bi.getHeight() / 2); } //The path of the watermark image is generally gif or png, so that transparency can be set ImageIcon imgIcon = new ImageIcon(icon); //Get the Image object. Image con = imgIcon.getImage(); //Transparency, minimum value is 0, maximum value is 1 float clarity = 0.6f; g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,clarity)); //Indicate 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 image result = "Icon watermark is added after image is completed"; } catch (Exception e) { e.printStackTrace(); } return result; }/** * Add a single image watermark to the image, and set the watermark image rotation angle* @param icon watermark image path (such as: F:/images/icon.png) * @param source Image path without watermark (such as: F:/images/6.jpg) * @param output The image path after adding a watermark (such as: F:/images/) * @param imageName Image name (such as: 11111) * @param imageType Image type (such as: jpg) * @param degree The rotation angle of the watermark image, 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 an image file!"; } //Load the icon into memory Image ic = ImageIO.read(ficon); //icon height int iheight = ic.getHeight(null); //read the source image into memory Image img = ImageIO.read(file); //Image width int width = img.getWidth(null); //Image height int height = img.getHeight(null); BufferedImage bi = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB); //Create a Graphics2D object with a specified BufferedImage. Graphics2D g = bi.createGraphics(); //x, the y-axis defaults to start from 0 coordinates int x = 0; int y = (height/2)-(iheight/2); //Set the jagged edge processing of the line segment g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BILINEAR); //Represent an image and convert from image space to user space before drawing g.drawImage(img.getScaledInstance(width,height,Image.SCALE_SMOOTH),0,0,null); if (null != degree) { //Set the watermark rotation g.rotate(Math.toRadians(degree),(double) bi.getWidth() / 2, (double) bi.getHeight() / 2); } //The path of the watermark image is generally gif or png, so the transparency can be set ImageIcon imgIcon = new ImageIcon(icon); //Get Image object. Image con = imgIcon.getImage(); //Transparency, minimum value is 0, maximum value is 1 float clarity = 0.6f; g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,clarity)); //Indicate 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 image result = "Icon watermark is added after the image is finished"; } catch (Exception e) { e.printStackTrace(); } return result; } /** * Add multiple text watermarks to the image, and set the watermark text rotation angle* @param source The image path that needs to be added (such as: F:/images/6.jpg) * @param outPut The image output path after adding the watermark (such as: F:/images/) * @param imageName Image name (such as: 11111) * @param imageType Image type (such as: jpg) * @param color The color of the watermark text* @param word Watermark text* @param degree The rotation angle of the watermark text, which 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 original image information File file = new File(source); if (!file.isFile()) { return file + " Not an image file!"; } Image img = ImageIO.read(file); //Image width int width = img.getWidth(null); //Image height int height = img.getHeight(null); //Text size int size = 50; //Add watermark BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D g = bi.createGraphics(); g.drawImage(img, 0, 0, width, height, null); //Set the watermark font style Font font = new Font("宋体", Font.PLAIN, size); //Set the watermark color according to the background of the picture g.setColor(color); int x = width/3; int y = size; int space = height/size; for(int i=0;i<space;i++){ //If the y-axis of the last coordinate is higher than height, exit directly if((y+size)>height){ break; } if (null != degree) { //Set the watermark rotation g.rotate(Math.toRadians(degree),(double) bi.getWidth() / 2, (double) bi.getHeight() / 2); } g.setFont(font); //Watermark position g.drawString(word, x, y); y+=(2*size); } g.dispose(); //Output image File sf = new File(output, imageName+"."+imageType); ImageIO.write(bi, imageType, sf); //Save image result = "Add Word watermark after image completion"; } catch (Exception e) { e.printStackTrace(); } return result; } /** * Add a single text watermark to the image, and set the watermark text rotation angle* @param source The image path that needs to be added with a watermark (such as: F:/images/6.jpg) * @param outPut The image output path after adding a watermark (such as: F:/images/) * @param imageName Image name (such as: 11111) * @param imageType Image type (such as: jpg) * @param color The color of the watermark text* @param word Watermark text* @param degree The rotation angle of the watermark text, which 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 original image information File file = new File(source); if (!file.isFile()) { return file + " Not an image file!"; } Image img = ImageIO.read(file); int width = img.getWidth(null); int height = img.getHeight(null); //Add watermark BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D g = bi.createGraphics(); g.drawImage(img, 0, 0, width, height, null); //Set the watermark font style Font font = new Font("宋体", Font.PLAIN, 50); //Set the watermark color according to the background of the picture g.setColor(color); if (null != degree) { //Set the 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; //Watermark position g.drawString(word, x, y); g.dispose(); //Output image File sf = new File(output, imageName+"."+imageType); ImageIO.write(bi, imageType, sf); //Save image result = "Add Word watermark after image completion"; } catch (Exception e) { e.printStackTrace(); } return result; } /** * Add mosaic to the image* @param source Original image path (such as: F:/images/6.jpg) * @param output After mosaicing, the path to save the image (such as: F:/images/) * @param imageName Image Name (such as: 11111) * @param imageType Image Type (such as: jpg) * @param size Mosaic size, that 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 = "Image mosaic error occurred"; try{ File file = new File(source); if (!file.isFile()) { return file + "Not an image file!"; } BufferedImage img = ImageIO.read(file); //Read the image int width = img.getWidth(null); //Original image width int height = img.getHeight(null); //Original image height BufferedImage bi = new BufferedImage(width,height, BufferedImage.TYPE_INT_RGB); //Mosaic grid size is too large or too small if (width < size || height < size) { return "Mosaic grid size is too large"; } if(size<=0){ return "The size of the mosaic grid is too small"; } int xcount = 0; //Draw the number in x direction int ycount = 0; //Draw the number in y direction 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 coordinate int y = 0;//y coordinate//Draw mosaic (draw rectangles and fill colors) Graphics2D g = bi.createGraphics(); for (int i = 0; i < xcount; i++) { for (int j = 0; j < ycount; j++) { //Mosaic rectangle size int mwidth = size; int mheight = size; if(i==xcount-1){ //The last one in the horizontal direction is not enough for one size mwidth = width-x; } if(j == ycount-1){ //The last one in the vertical direction is not enough for one size mheight = height-y; } //The RGB value of the rectangle color takes the center pixel 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;// Calculate the y coordinate of the next rectangle} y = 0;// Restore the y coordinate x = x + size;// Calculate the x coordinate} g.dispose(); File sf = new File(output, imageName+"."+imageType); ImageIO.write(bi, imageType, sf); // Save the image result = "Mosaic success"; }catch(Exception e){ e.printStackTrace(); } return result; }}For more Java-related content, readers who are interested in this site can view the topics: "Summary of Java Image Operation Skills", "Summary of Java Date and Time Operation Skills", "Summary of Java Operation DOM Node Skills", "Summary of Java File and Directory Operation Skills" and "Tutorials of Java Data Structure and Algorithm".
I hope this article will be helpful to everyone's Java programming.