兩點注意:
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>