一、基础类
import java.awt.*;
public class ImageText {
//文字内容或图片路径
private String text;
//------------------文字属性-------------------
//字体颜色和透明度
private Color color;
//字体和大小
private Font font;
//------------------图片属性-------------------
//图片宽
private int width;
//图片高
private int height;
//------------------坐标属性-------------------
//所在图片的x坐标
private int x;
//所在图片的y坐标
private int y;
//set和get部分省略
public ImageText() {
}
//用于添加图片
public ImageText(String text, Color color, Font font, int x, int y) {
this.text = text;
this.color = color;
this.font = font;
this.x = x;
this.y = y;
}
//用于添加文本
public ImageText(String text, int width, int height, int x, int y) {
this.text = text;
this.width = width;
this.height = height;
this.x = x;
this.y = y;
}
}
二、工具
/**
*
* @param srcImgPath 源图片路径
* @param targetImgPath 保存图片路径
* @param strList 文字集合
* @param imgList 图片集合
*/
public static void writeImage1(String srcImgPath, String targetImgPath, List<ImageText> strList, List<ImageText> imgList){
try (FileOutputStream outImgStream = new FileOutputStream(targetImgPath)){
//读取原底片信息
File srcImgFile = new File(srcImgPath);//得到文件
BufferedImage srcImg = ImageIO.read(srcImgFile);//文件转化为图片
int srcImgWidth = srcImg.getWidth();//获取图片的宽
int srcImgHeight = srcImg.getHeight();//获取图片的高
//添加文字
BufferedImage bufImg = new BufferedImage(srcImgWidth, srcImgHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = bufImg.createGraphics();
g2d.drawImage(srcImg, 0, 0, srcImgWidth, srcImgHeight, null);
for (ImageText strDTO : strList) {
g2d.setColor(strDTO.getColor()); //根据图片的背景设置水印颜色
g2d.setFont(strDTO.getFont()); //设置字体
g2d.drawString(strDTO.getText(), strDTO.getX(), strDTO.getY()); //画出水印
}
//添加图片
for (ImageText imgDTO : imgList) {
BufferedImage img = ImageIO.read(new File(imgDTO.getText()));
BufferedImage imgNew = new BufferedImage(imgDTO.getWidth(), imgDTO.getHeight(), BufferedImage.TYPE_INT_RGB);
g2d.drawImage(img, imgDTO.getX(), imgDTO.getY(), imgNew.getWidth(), imgNew.getHeight(), null);
}
g2d.dispose();
// 输出图片
ImageIO.write(bufImg, "jpg", outImgStream);
} catch (Exception e) {
e.printStackTrace();
}
}
三、测试
public static void main(String[] args) {
//=========================================自行发挥================================
//自己真实的地址:(若是文件流,连同工具部分一同修改就好);
String srcImgPath="C:\\Users\\levoe\\Desktop\\证件\\图片1.png"; //源图片地址
String tarImgPath="C:\\Users\\levoe\\Desktop\\证件\\TEMP\\测试1.png"; //目标图片的地址
//==============================================================================
//获取数据集合
List<ImageText> list = new ArrayList<>();
list.add(new ImageText("测试文本内容",Color.BLACK,new Font("仿宋_GB2312", Font.PLAIN, 12), 6, 63));
List<ImageText> imgList = new ArrayList<>();
imgList.add(new ImageText("C:\\Users\\ZhiPengyu\\Desktop\\证件\\img1.jpg",35,44, 6, 16));
//操作图片:
writeImage1(srcImgPath, tarImgPath, list,imgList);
}