JAVA Graphics2D synthesis and image add text

Posted by kaedus on Mon, 07 Oct 2019 05:22:50 +0200

Due to business needs, it needs to be on the background map.

1. Write the title and author of the research paper dynamically and change the line automatically.

2., WeChat small program two-dimensional code is synthesized on the background map.

The effect is as follows

The code is as follows to facilitate writing this into a tool class

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.InputStream;

import javax.imageio.ImageIO;


/**
* <p>Title: CompositePicture</p>
* <p>Description: Picture merging</p>
*/
public class CompositePicture {
	
	/**
	 * 
	 * @param path  Address of loading background picture
	 * @param documentId  The label of my research paper is used to synthesize the name of the new map. Everyone can refer to it according to their own needs.
	 * @param inputStream  Small program two-dimensional code input stream does not know how to generate small programs can be up and down developers to see on api or online to find resources.
	 * @param title The title of the research paper is to show the text on the background map, which can be replaced by the user name or something according to their own needs. 
	 * @param authorNameAndDate The author of the research paper also wants to display the text on the background map, which can be replaced by user names or other words according to his own needs. 
	 * @param fontSize Size of fonts
	 * @return
	 */
	public static String compositePicture(String path,Long documentId,InputStream inputStream, String title, String authorNameAndDate, int fontSize) {
		String originalFilename = documentId+".png";
		try {
			// Load background images
			BufferedImage imageLocal = ImageIO.read(new File(path + "share_background.png"));
			int srcImgWidth = imageLocal.getWidth(null);
			int srcImgHeight = imageLocal.getHeight(null);
			
			// Loading WeChat small program two-dimensional code and converted to BufferedImage
			BufferedImage imageCode = ImageIO.read(inputStream);
			// Using background images as templates
			Graphics2D g = imageLocal.createGraphics();
			// Eliminate text jagged
			g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
			// Add user two-dimensional code (address, left margin, upper margin, picture width, picture height, unknown) to the template.
			g.drawImage(imageCode, 367, imageLocal.getHeight() - 170, 150, 150, null);
			Font font1 = new Font("Microsoft YaHei", Font.BOLD, fontSize);// Property settings for adding fonts
			g.setFont(font1);
			Color color1 = new Color(100,0,0);
			g.setColor(color1);
			
			String waterMarkContent = title;
			// Interception of research headlines such as Science and Technology: MWC: 5G and Edge Computing Equipment Design and Production Ideas is more clearly displayed as Science and Technology:
			g.drawString(waterMarkContent.substring(0,waterMarkContent.indexOf(": ")+1),20,200);
			// Interception of research headlines such as: Science and Technology: MWC: 5G and Edge Computing Equipment Design and Production Ideas are more clearly displayed for MWC: 5G and Edge Computing Equipment Design and Production Ideas are clearer.
			waterMarkContent=waterMarkContent.substring(waterMarkContent.indexOf(": ")+1);
			// Getting the Total Length of Watermarking Text
			int fontlen = getWatermarkLength(waterMarkContent, g);
			int line = fontlen / srcImgWidth;// How many lines should the text length be relative to the width of the picture?

			// Text Overlay, Automatic Line-Breaking Overlay
			int tempX = 20;
			int tempY = 260;
			int tempCharLen = 0;// Single character length
			int tempLineLen = 0;// Temporary calculation of the total length of a single line character
			System.out.println("Total length of watermarking text:" + fontlen + ",image width:" + srcImgWidth + ",Picture height:" + srcImgHeight+ ",Number of characters:" + waterMarkContent.length()+ ",Number of text rows:" + line+",x Initial coordinates:" + tempX+",y Initial coordinates:" + tempY);
			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < waterMarkContent.length(); i++) {
				char tempChar = waterMarkContent.charAt(i);
				tempCharLen = getCharLen(tempChar, g);//Get the length of the title

				if ((tempLineLen) >= srcImgWidth) {
					g.drawString(sb.toString(), tempX, tempY);// The length has reached a full line, and the text is superimposed.
					
					sb.delete(0, sb.length());// Empty content, add again
					
					tempY += fontSize+10;// The length has reached one line, the position of Y plus 10 character height

					tempLineLen =0;
				}
				sb.append(tempChar);// Additional character
				tempLineLen += tempCharLen;
			}
			g.drawString(sb.toString(), tempX, tempY);// Finally superimpose the rest of the text
			Font font2 = new Font("Microsoft YaHei", Font.PLAIN, 23);// Property settings for adding fonts
			g.setFont(font2);
			Color color2 = new Color(255,255,255);
			g.setColor(color2);
			g.drawString(authorNameAndDate,20, imageLocal.getHeight() - 220);
			g.dispose();
			
			// Complete template modification
			g.dispose();
			// Determine whether the address path of the new file exists, and create one if it does not.
			File outputfile = new File(path+originalFilename);
			if (!outputfile.getParentFile().exists()) {
				outputfile.getParentFile().mkdirs();
			}
			// Generate new synthesized user two-dimensional code and write new pictures
			ImageIO.write(imageLocal, "png", outputfile);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return originalFilename;
	}
	
	/**
	 * 
	 * @param c Strings that need to be written on the background map
	 * @param g Graphics2D java Processing Objects for Composite Picture Writing
	 * @return
	 */
	public static int getCharLen(char c, Graphics2D g) {
		return g.getFontMetrics(g.getFont()).charWidth(c)+3;
	}

	/**
	 * Getting the Total Length of Watermarking Text
	 * 
	 * @paramwaterMarkContent Watermarking text
	 * @paramg
	 * @return Total length of watermarking text
	 */
	public static int getWatermarkLength(String waterMarkContent, Graphics2D g) {
		return g.getFontMetrics(g.getFont()).charsWidth(waterMarkContent.toCharArray(), 0, waterMarkContent.length());
	}

}

Here are a few points to note

1. The words written on the images synthesized under windows can be seen, but when deployed to the linux server, they will be scrambled.

The reason is that there is no corresponding font on the linux server

Solutions You can refer to another blog of mine. https://mp.csdn.net/postedit/98849793

Topics: Java Linux REST Windows