如何通过 Java HTTP 服务器发送图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26880192/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to send an image over Java HTTP server
提问by Mohammad Daei
I'm developing an HTTP server using HttpServer
and HttpHandler
.
我正在使用HttpServer
和开发 HTTP 服务器HttpHandler
。
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 (e.g., 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 字节的数据。
回答by JB Nizet
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();
回答by Evan Knowles
DataBufferByte
stores its data in banks. getData()
retrieves only the first bank, so you're declaring a length of only the first bank and then writing only the first bank.
DataBufferByte
将其数据存储在银行中。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