最近项目中涉及到了打印证件,证件内容是从数据库中取,通过思考,将取到的信息打在图片上并保存到文件夹下的方法比较可取,减少后期修改的麻烦
该方法在java类里完成
//方法的参数,第一个为做为背景的原图路径,第二个为图片生成的路径,第三个为图片水印路径,后三个为文字水印内容
public void createStringMark(String backImgPath, String filePath, String logoPath ,String markContent1, String markContent2, String markContent3) throws Exception {
ImageIcon imgIcon = new ImageIcon(backImgPath);
Image theImg = imgIcon.getImage();
int width = theImg.getWidth(null);
int height = theImg.getHeight(null);
File file = new File(filePath);
BufferedImage bimage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = (Graphics2D) bimage.createGraphics();
Font font = new Font("宋体", Font.BOLD, 32); //能够打印中文并不乱码
g.setFont(font);
g.setColor(Color.black);
g.setBackground(Color.white);
g.drawImage(theImg, 0, 0, null);
g.drawString(markContent1, 560, 460);
g.drawString(markContent2, 570, 600);
g.drawString(markContent3, 520, 750);
ImageIcon icoADD = new ImageIcon(logoPath);
Image imgADD = icoADD.getImage();
g.drawImage(imgADD, 60, 391, 293, 409, null); //第二个与第三个参数为图片坐标,第四与第五个参数为图片尺寸
g.dispose();
try {
FileOutputStream out = new FileOutputStream(filePath);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bimage);
param.setQuality(12, true);
encoder.encode(bimage, param);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}