JAVA開發經驗(二):常用工具類2.8-IO-圖片合併並添加文字(ImageMergedUtil)

摘要說明:

ImageMergedUtil主要合成圖片並添加文字,比如經常遇到的背景二維碼生成海報

Maven依賴:

效果:

            +                              

java工具類:


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

import javax.imageio.ImageIO;

public class ImageMergedUtil {
	/**
	 * 合成圖片並添加文字
	 * 
	 * @param tempImage
	 *            模版圖片
	 * @param mergedImage
	 *            疊加圖片
	 * @param left
	 *            疊加圖片左邊距
	 * @param top
	 *            疊加圖片上邊距
	 * @param width
	 *            疊加圖片寬帶
	 * @param height
	 *            疊加圖片高度
	 * @param str
	 *            文字
	 * @param font
	 *            文字字體
	 * @param fontLeft
	 *            文字左邊距
	 * @param fonTop
	 *            文字上邊距
	 * @param outputfile
	 *            最終合成文件
	 * @throws IOException
	 */
	public static void merged(File tempImage, File mergedImage, int left,
			int top, int width, int height, String str, Font font,
			int fontLeft, int fonTop, File outputfile) throws IOException {
		// 加載模版圖片
		BufferedImage imageLocal = ImageIO.read(tempImage);
		// 加載疊加圖片
		BufferedImage imageCode = ImageIO.read(mergedImage);
		Graphics2D g = imageLocal.createGraphics();
		// 在模板上添加疊加圖片(地址,左邊距,上邊距,圖片寬度,圖片高度,未知)
		g.drawImage(imageCode, left, top, width, height, null);
		// 添加文本說明
		if (str != null) {
			// 設置文本樣式
			g.setFont(font);
			g.setColor(Color.RED);
			g.drawString(str, fontLeft, fonTop);
		}
		// 完成模板修改
		g.dispose();
		ImageIO.write(imageLocal, "png", outputfile);

	}

	public static void main(String[] args) {
		File tempImage = new File("d://temp.png");
		File mergedImage = new File("d://qrcode.png");
		File outputfile = new File("d://outputfile.png");
		Font font = new Font("PingFangSC-Regular", Font.PLAIN, 35);
		try {
			ImageMergedUtil.merged(tempImage, mergedImage, 220, 761, 300, 300,
					"xxx邀請你使用xxx", font, 220, 1187, outputfile);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

 

發佈了107 篇原創文章 · 獲贊 40 · 訪問量 15萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章