在Java中绘制形状并返回到HTTP请求中的浏览器

时间:2018-04-24 17:23:37

标签: javascript java canvas awt

我有一个Node应用程序可以绘制x,y图形并将其传输回浏览器。我使用HTML画布并将图像流回到我做的UI:

// create the canvas, set size and draw the x,y points
// ...
// ...

var buf = canvas.toBuffer();
var graph = buf.toString('base64');

var data = JSON.stringify({
    graph: graph
});

var headers = {
    'Content-Type': 'image/png'
};

res.writeHead(200, headers);
res.end(data);

现在我想用Java重写这个功能。我正在考虑将java.awt.Graphics2D用于此目的。我在这里创建了图片:

Graphics g;
Graphics2D g2 = (Graphics2D) g;

g2.setColor(Color.red);
g2.drawRect(10,10,100,100);

如何在HTTP请求中将此内容返回给浏览器?

1 个答案:

答案 0 :(得分:0)

一种简单明了的方法是:

  1. 撰写embedded Jetty application
  2. 将Graphics2D实例转换为RenderedImage界面。
  3. 通过a known image format将图形对象写入ImageIO
  4. 通过custom handler将渲染图像导出到浏览器。
  5. 这可能类似于:

    package org.eclipse.jetty.embedded;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.eclipse.jetty.server.Request;
    import org.eclipse.jetty.server.handler.AbstractHandler;
    
    public class ImageHandler extends AbstractHandler {
    
        public ImageHandler() { }
    
        public void handle( final String target,
                            final Request baseRequest,
                            final HttpServletRequest request,
                            final HttpServletResponse response )
          throws IOException, ServletException
        {
          final byte[] image = getImage();
          response.setHeader( "Content-Type", "image/png" );
          response.setHeader( "Content-Length", image.length );
          response.setStatus( HttpServletResponse.SC_OK );
          response.getOutputStream().write( image );
    
          baseRequest.setHandled( true );
        }
    }
    

    getImage()方法:

    public byte[] getImage() throws IOException {
        final int width = getWidth();
        final int width = getHeight();
        final BufferedImage image = new BufferedImage( width, height, TYPE_INT_RGB );
        final Graphics2D graphics = createGraphics2D();
        graphics.drawImage( image, null, null );
    
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write( image, "png", baos );
        baos.flush();
    
        final byte[] result = baos.toByteArray();
        baos.close();
    
        return result;
    }
    

    方法Graphics2D createGraphics2D() { ... }的内容完全取决于您。还必须指定图像尺寸(宽度和高度)。 TYPE_INT_RGB常量来自BufferedImage

    请注意,可以组合通过ImageIO写入和导出到响应输出流的步骤。这样可以直接将图像写入浏览器,而无需先创建数组,从而提高感知的渲染速度。