How to send an image via Java HTTP server

I am developing an HTTP server using HttpServer

and HttpHandler

.

The server should respond to clients with XML data or images.

So far I have developed implementations HttpHandler

that respond to clients with XML data, but I have not been able to implement HttpHandler

that reads an image from a file and sends it to a client (like a browser).

The image doesn't have to load completely 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.

+6


source to share


2 answers


You're working too hard here: decode the image and store it in memory. You shouldn't try to read the file as an image. It's useless. All browser needs are bytes that are in the image file. So you should just send bytes to 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();

      

+11


source


DataBufferByte

stores its data in banks. getData()

fetches only the first bank, so you only declare the length of the first bank, and then only write the first bank.

Instead of the current line of entry, try this (untested) instead:



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

      

0


source







All Articles