好用的图片上固定位置加文字的工具类
package com.zjtx.util;
import com.zjtx.util.exception.ServiceException;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.List;
import java.util.*;
/**
* 图片固定位置加文字工具类
* @author WangDeyu
* */
public class ImageIOUtils {
/**
* 生成年底活动用的成绩图片
* @param oldImgPath (原图片地址)
* @param newImgPath (填充文字后的图片地址)
* @param list (填充图片的文字内容)
* */
public static void generateActivityImage(String oldImgPath, String newImgPath, List<Map<String,Object>> list) throws Exception{
ImageIcon imgIcon = new ImageIcon(oldImgPath);
Image img = imgIcon.getImage();
int width = img.getWidth(null);
int height = img.getHeight(null);
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = bufferedImage.createGraphics();
g.drawImage(img, 0, 0, null);
//设置字体和字体颜色
Font font = new Font("黑体",Font.BOLD, 33);
g.setBackground(Color.white);
g.setPaint(new Color(0,18,252));
g.setFont(font);
FontMetrics fm = g.getFontMetrics(font);
for (Map<String,Object> map : list){
String name = (String) map.get("name");
Integer x1 = (Integer) map.get("x1");
Integer x2 = (Integer) map.get("x2");
Integer y = (Integer) map.get("y");
//获取文字长度
int textWidth = fm.stringWidth(name);
//计算文字根据横坐标居中
g.drawString(name,(x1+x2 - textWidth) / 2 , y);
}
g.dispose();
try {
FileOutputStream out = new FileOutputStream(newImgPath);
ImageIO.write(bufferedImage, "png", out);
out.close();
} catch (FileNotFoundException e) {
throw new ServiceException("生成图片文字失败:",e);
}
}
public static void main(String[] args) throws Exception{
//文字内容
List<String> name = Arrays.asList("疼他爹没错就是我", "骚哦", "666", "怎肥事?", "好气哦", "滑稽果");
//文字x轴坐标1(因为要根据一个范围居中,所以有两个x坐标)
List<Integer> x1 = Arrays.asList(162, 270, 140, 465, 238, 534);
//文字x轴坐标2
List<Integer> x2 = Arrays.asList(270, 356, 225, 550, 311, 608);
//文字y轴坐标
List<Integer> y = Arrays.asList(50, 100, 150, 200, 250, 300);
List<Map<String, Object>> imgList = new ArrayList<>();
int size = name.size();
for (int i = 0; i < size; i++) {
Map<String, Object> map = new HashMap<>(16);
map.put("name", name.get(i));
map.put("x1", x1.get(i));
map.put("x2", x2.get(i));
map.put("y", y.get(i));
imgList.add(map);
}
generateActivityImage( "D:\\img\\temp.png", "D:\\img\\new.png", imgList);
}
}
效果图