angular4 + springboot 从后端生成的图片,模拟任务管理器里cpu利用率的显示

两点注意:

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;
    }

}

友情帮助:https://stackoverflow.com/questions/21837851/angularjs-ng-src-in-ie8-image-not-loaded-and-unsafe-added-to-path

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值