简体   繁体   English

如何通过Java HTTP服务器发送映像

[英]How to send an image over Java HTTP server

I'm developing an HTTP server using HttpServer and HttpHandler . 我正在使用HttpServerHttpHandler开发一个HTTP服务器。

The server should response to clients with XML data or images. 服务器应该使用XML数据或图像响应客户端。

So far, I have developed HttpHandler implementations which respond to the clients with the XML data but I couldn't implement a HttpHandler which reads the image from file and send it to the client (eg, a browser). 到目前为止,我已经开发了HttpHandler实现,它们使用XML数据响应客户端,但是我无法实现从文件读取图像并将其发送到客户端(例如,浏览器)的HttpHandler

The image should not be loaded fully into memory so I need some kind of streaming solution. 图像不应该完全加载到内存中,因此我需要某种流式解决方案。

public class ImagesHandler implements HttpHandler {
    @Override
    public void handle(HttpExchange arg0) throws IOException {
        File file=new File("/root/images/test.gif");
        BufferedImage bufferedImage=ImageIO.read(file);

        WritableRaster writableRaster=bufferedImage.getRaster();
        DataBufferByte data=(DataBufferByte) writableRaster.getDataBuffer();

        arg0.sendResponseHeaders(200, data.getData().length);
        OutputStream outputStream=arg0.getResponseBody();
        outputStream.write(data.getData());
        outputStream.close();
    }
}

This code just sends 512 bytes of data to the browser. 此代码只向浏览器发送512字节的数据。

You're doing way too much work here: decoding the image, and storing it in memory. 你在这里做了太多工作:解码图像,并将其存储在内存中。 You shouldn't try to read the file as an image. 您不应该尝试将文件作为图像读取。 That is useless. 那没用。 All the browser needs is the bytes that are in the image file. 浏览器的所有需求都是图像文件中的字节数。 So you should simply send the bytes in the image file as is: 所以你应该简单地按原样发送图像文件中的字节:

File file = new File("/root/images/test.gif");
arg0.sendResponseHeaders(200, file.length());
// TODO set the Content-Type header to image/gif 

OutputStream outputStream=arg0.getResponseBody();
Files.copy(file.toPath(), outputStream);
outputStream.close();

DataBufferByte stores its data in banks. DataBufferByte将其数据存储在银行中。 getData() retrieves only the first bank, so you're declaring a length of only the first bank and then writing only the first bank. getData()仅检索第一个库,因此您只声明第一个库的长度,然后只写第一个库。

Instead of your current write line, try this instead (untested): 而不是你当前的写行,而是尝试这个(未经测试):

arg0.sendResponseHeaders(200, data.getDataTypeSize(TYPE_BYTE));
OutputStream outputStream=arg0.getResponseBody();
for (byte[] dataBank : data.getBankData()) {
  outputStream.write(dataBank);
}
outputStream.close

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM