两点注意:
1、后端返回数据 byte[]
2、前端<image [src]="url">
this.url = location.protocol + '//' + location.hostname + ':8888' + '/image/{name}/{time}'
这里8888是服务的端口。name和time是参数。
controller: 纯手打,ImageUtil 是 帮助快速生成图片的工具类, draw是回调画法,返回对象是uitl本身,可以继续getImage()或者getByte(),或者再save()保存为文件。Counter对象的设计是为了方便更好的在一些函数内进行计算。
private static final int WIDTH = 480;
private static final int HEIGHT = 360;
@RequestMapping(value="/{name}/{time}", method = RequestMethod.GET)
@ResponseBody
public byte[] image(@PathVariable String name, @PathVariable String time, HttpServletRequest request) {
int excursion = 10; // 图片偏移量
Object object = request.getSession().getAttribute(name);
final Counter counter = object != null ? (Counter) object : Counter.create();
byte[] buffer = ImageUtil.me().draw(WIDTH, HEIGHT, 1, (graphics) -> {
graphics.setColor(Color.WHITE);
graphics.fillRect(0, 0, WIDTH, HEIGHT);
graphics.setColor(Color.BLACK);
Point p = new Point(0,counter.getCount() == 0 ? HEIGHT - DateUtil.random(HEIGHT) : counter.getCount());
int x, y;
for (x = 0; x < WIDTH; x += excursion) {
y = HEIGHT - DateUtil.random(HEIGHT);
graphics.drawLine(p.x, p.y, x, y);
p.x = x;
p.y = y;
counter.setCount(p.y);
}
request.getSession().setAttribute(name, counter);
}).getBytes();
return buffer;
}
ts:
iamges = ['/image/a', '/image/b', '/image/c', '/image/d', '/image/e', '/image/f'];
urls = [];
ngOInit() {
setInterval( () => {
this.urls = [];
const imageUrl = location.protocol + '//' + location.hostname + ':8888';
this.iamges.forEach( url => {
url = imageUrl + url + '/' + new Date().getTime();
this.urls.push(url);
});
}, 1000);
}
html:
<div class='cpu' *ngFor="let url of this.urls">
<img [src]="{{url}}">
</div>
上述有一个问题,如果我返回的数据有中文怎么办,肯定要配置转码,然后上面的方法可能就不管用了。
那么,解决方法就是改变图片流的返回方式,不再用byte数组的方式而是直接用ImageIO提供的静态方法
方法就不要返回值了,用void就可以了,前端代码不需要改变。
private static final int WIDTH = 480;
private static final int HEIGHT = 360;
@RequestMapping(value="/{name}/{time}", method = RequestMethod.GET)
@ResponseBody
public void image(@PathVariable String name, @PathVariable String time, HttpServletRequest request) {
int excursion = 10; // 图片偏移量
Object object = request.getSession().getAttribute(name);
final Counter counter = object != null ? (Counter) object : Counter.create();
BufferImage image = ImageUtil.me().draw(WIDTH, HEIGHT, 1, (graphics) -> {
graphics.setColor(Color.WHITE);
graphics.fillRect(0, 0, WIDTH, HEIGHT);
graphics.setColor(Color.BLACK);
Point p = new Point(0,counter.getCount() == 0 ? HEIGHT - DateUtil.random(HEIGHT) : counter.getCount());
int x, y;
for (x = 0; x < WIDTH; x += excursion) {
y = HEIGHT - DateUtil.random(HEIGHT);
graphics.drawLine(p.x, p.y, x, y);
p.x = x;
p.y = y;
counter.setCount(p.y);
}
request.getSession().setAttribute(name, counter);
}).getImage();
try{
ImageIO.write(image, "JPEG", response.getOutputStream());
}catch(Exception e){
}
}
ImageUtil
public class ImageUtil {
private Log log = LogFactory.getLog();
private BufferedImage image;
private Object [] types = {"jpg","png","gif","bmp"};
public BufferedImage getImage() {
return image;
}
public byte[] getBytes() {
byte[] bytes = null;
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
try {
ImageIO.write(image, "jpg", byteArrayOutputStream);
bytes = byteArrayOutputStream.toByteArray();
}catch (Exception e) {
log.error(e);
}finally {
try {
byteArrayOutputStream.close();
}catch (IOException e) {
e.printStackTrace();
}
}
return bytes;
}
private static ImageUtil $this;
private synchronized void setImage(BufferedImage image) {
this.image = image;
}
private static class LazyInit{
private static ImageUtil INITIALIZATION = new ImageUtil();
}
public static ImageUtil me() {
$this = LazyInit.INITIALIZATION;
return LazyInit.INITIALIZATION;
}
public ImageUtil draw(int width,
int height,
int imageType,
DrawImageCallBack callBack) {
BufferedImage image = null;
try {
image = new BufferedImage(width,height,imageType);
if (image == null) {
throw new RuntimeException("image create error");
}
Graphics graphics = image.getGraphics();
callBack.draw(graphics);
if (graphics != null) {
graphics.dispose();
}
} catch (Exception e) {
log.error(e);
}
this.setImage(image);
return $this;
}
public ImageUtil save (String... params) {
String type = (String) ArraysUtil.me().getOneOfIt(types);
String name = StringUtil.createCode(10, true);
if (null == this.getImage()) {
throw new RuntimeException("can not save, image is null.");
}
if (params.length > 0) {
type = params[0];
}
if (params.length > 1 && params.length <= 2) {
name = params[1] + "." + type;
} else if (params.length > 2) {
name = params[1] + "//" + (StringUtil.isBlank(params[2]) ? StringUtil.createCode(5, true) : params[2]) + "." + type;
} else {
name += "." + type;
}
try {
ImageIO.write(this.getImage(), type, FileUtil.me().create(name));
} catch (Exception e) {
if (("file is exist").equals(e.getMessage())) {
try {
ImageIO.write(this.getImage(), type, new File(name));
} catch (Exception ioe) {
log.error(ioe);
}
} else log.error(e);
}
return $this;
}
}