前端引入一个动态图片,后台读取数据库的文字生成并返回
<img src="http://localhost:8080/get" />
后台代码:
工具类
package com.example.demo.util;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
/**
* Created with IntelliJ IDEA.
* Project:springboothelloworld
* User: Bluce Young
* Date: 2019/12/20 9:45
* Description: www.teacheryoung.com
*/
public class ImageUtil {
/**
* 字符串转成BufferedImage
* @param width
* @param height
* @param str
* @return
*/
public BufferedImage stringToImage(int width,int height,String str){
BufferedImage bi = new BufferedImage
(width,height,BufferedImage.TYPE_INT_RGB);//INT精确度达到一定,RGB三原色,高度70,宽度150
//得到它的绘制环境(这张图片的笔)
Graphics2D g2 = (Graphics2D) bi.getGraphics();
g2.fillRect(0,0,width,height);//填充一个矩形 左上角坐标(0,0),宽70,高150;填充整张图片
//设置颜色
g2.setColor(Color.WHITE);
g2.fillRect(0,0,width,height);//填充整张图片(其实就是设置背景颜色)
g2.setColor(Color.RED);
g2.drawRect(0,0,width-1,height-1); //画边框
g2.setFont(new Font("Consolas", Font.PLAIN,18)); //设置字体:字体、字号、大小
g2.setColor(Color.BLACK);//设置背景颜色
g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);//设置抗锯齿
g2.setPaint(new Color(0, 0, 0, 64));//阴影颜色
g2.drawString(str,3,26);//先绘制阴影
g2.setPaint(Color.BLACK);//正文颜色
//g2.drawString(txt, x, y);//用正文颜色覆盖上去
g2.drawString(str,3,26); //向图片上写字符串
return bi;
}
/**
* 输出一个图像到httpResponse流
* @param bi
* @param httpServletResponse
* @throws IOException
*/
public void writeImageToResponse(BufferedImage bi, HttpServletResponse httpServletResponse) throws IOException {
ByteArrayOutputStream stream=new ByteArrayOutputStream();
ImageIO.write(bi,"JPEG",stream);
byte[] img =stream.toByteArray();
stream.close();
httpServletResponse.setContentType("image/png");
OutputStream os = httpServletResponse.getOutputStream();
os.write(img);
os.flush();
os.close();
}
}
控制器
package com.example.demo.controller;
import com.example.demo.util.ImageUtil;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
/**
* Created with IntelliJ IDEA.
* Project:springboothelloworld
* User: Bluce Young
* Date: 2019/11/29 16:37
* Description: www.teacheryoung.com
*/
@RestController
public class MainController {
@RequestMapping(value = "/get",produces = MediaType.IMAGE_JPEG_VALUE)
public String test(HttpServletResponse httpServletResponse) throws IOException {
ImageUtil imageUtil=new ImageUtil();
String str="select hahah fewff -name -p -ss";//这里读取数据库
BufferedImage bufferedImage = imageUtil.stringToImage(777, 41, str);
imageUtil.writeImageToResponse(bufferedImage,httpServletResponse);
return "success";
}
}