Java生成图片在前端展示并可下载
项目中使用场景
我在项目中使用到这个生成图片是动态生成的,
场景是学生查看准考证,根据学生信息来生成准考证展示,并可以下载
后台代码(一)生成图片方法
主要是用到了Java中的BufferedImage类,得到画笔对象,
在图片上画出对应的信息,验证码也是可以用这个做,
话不多说,上代码
public static void drawImage(String img,String sImg,String name,String address,
String starttime,String endtime,OutputStream outputStream) throws Exception {
//读入大图片到内存
//我在这里读图片路径这么复杂是因为项目部署到服务器上后只有这样才能获取到
//本地测可以直接使用绝对路径
InputStream is = DrawingUtil.class.getClassLoader().getResourceAsStream(img);
//创建
BufferedImage bufferImg = ImageIO.read(is);
//得到画笔对象
Graphics g = bufferImg.getGraphics();
//创建附加的小图片对象
//这里也是一样上面读进流的方法在这个Image对象里不行,换成这个ClassPathResource读URL就行
ClassPathResource classP = new ClassPathResource(sImg);
ImageIcon imgIcon=new ImageIcon(classP.getURL());
//得到Image对象
Image simg =imgIcon.getImage();
//将小图片绘到大图片上,位置信息:(x,y)
g.drawImage(simg,1241,433,null);
//设置字体颜色
g.setColor(new Color(78,76,75));//78,76,75
//设置字体、字体大小
Font f = new Font("微软雅黑", Font.PLAIN, 38);
g.setFont(f);
//图片上绘制字符串内容,位置信息(x,y)
g.drawString(name, 500,489);
//这个drawText方法功能是长文本画入图片时自动换行的
drawText(g.getFont().getSize(),500,979,700,5,g,address);
g.drawString(starttime, 500, 1337);
g.drawString(endtime, 500, 1405);
g.dispose();
//我这里传进来的输出流是从controller传进来的
//在这里是把bufferImg里画好的内容输出到outputStream里
ImageIO.write(bufferImg, "jpeg", outputStream);
//关闭流
is.close();
}
后台代码(二)springMvc方法展示图片
controller方法里主要用到了http头部,对浏览器的判断,以及ByteArrayOutputStream流,
还有是springMvc的ResponseEntity类,它能完成下载的功能
上代码
/**
* 根据请求的id查询数据生成图片
* @param
* @return
*/
@RequestMapping(value = "/createImg",method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<byte[]> draw(String studentNo,String examBatchId, HttpServletRequest req, HttpServletResponse resp) throws Exception {
//获取准考证信息
Map<String,String> stu = getStudent(studentNo,examBatchId);
ResponseEntity<byte[]> entity = null;
ByteArrayOutputStream bo=null; //字节流
String fileName=UUID.randomUUID().toString() +".jpg";
//一般浏览器状态码CREATED就行
HttpStatus statusCode = HttpStatus.CREATED;
String header = req.getHeader("User-Agent").toUpperCase();
try {
//判断浏览器是不是IE
if (header.contains("MSIE") || header.contains("TRIDENT") || header.contains("EDGE")) {
fileName = URLEncoder.encode(fileName, "gbk");
fileName = fileName.replace("+", "%20"); // IE下载文件名空格变+号问题
//IE可以设置为OK
statusCode = HttpStatus.OK;
} else {
fileName = new String(fileName.getBytes("gbk"), "ISO8859-1");
}
//创建要用的输出流
bo=new ByteArrayOutputStream();
String simg="static/images/ca.jpg";
//生成图片流
DrawingUtil.drawImage("static/images/ca1.jpg",
simg,
stu.get("name"),
stu.get("address"),
stu.get("startTime"),
stu.get("endTime"),bo);
//设置头信息
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
//UUID作为文件名
headers.setContentDispositionFormData("attachment",fileName);
//获取字节数据
byte[] bytes = bo.toByteArray();
//交给spring
entity = new ResponseEntity<byte[]>(bytes, headers, statusCode);
} finally {
try {
assert bo != null;
bo.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return entity;
}
前端代码
前端就简单了,在vue里使用
<div>
<el-button class="btn_ea" size="mini" @click="downImage">下载</el-button>
</div>
<img align="center" width="70%" height="1300" :src="imgUrl"/>
mounted () {
this.initStu()
},
methods: {
initStu () {
this.imgUrl = '/certImage/createImg?examBatchId=' + this.$route.query.examBatchId
},
downImage () {
window.location.href = 'http://xxx:xxx/certImage/createImg?examBatchId=' + this.$route.query.examBatchId
}
最后
希望这篇博客能对遇到问题的你有帮助