开发者

In Java 1.6 how to serve a JPEG in memory through an HTTPHandler?

开发者 https://www.devze.com 2023-01-21 16:37 出处:网络
I am working on creating a simple HTTP server as part of a Java server.One component of this Java server is to capture images live from a webcam.Currently I am writing the images out to disk, and serv

I am working on creating a simple HTTP server as part of a Java server. One component of this Java server is to capture images live from a webcam. Currently I am writing the images out to disk, and serving them through Apache.

What I want to do in the end though is write the JPEG to memory in a List of JPEG objects and then have a HTTPHandler that will serve the appropriate image when requested.

I don't see any clear way to do this. Anyone have any ideas?

Here is how I am getting the images, using LTI CIVIL as the capture library - This is saving them to disk - I want to store them in memory:

try
  {
   String fileName = "image" + System.currentTimeMillis() + ".jpg";

FileOutputStream os = new FileOutputStream(FILE_PATH + fileName);
final JPEGImageEncoder jpeg = JPEGCodec.createJPEGEncoder(os);
jpeg.encode(AWTImageConverter.toBufferedImage(image));

os.close();

log.info("Got image as filename: " + fileName)开发者_Go百科;
}
catch (Exception e)
{
 log.error("An error occured", e);
}


If you use a ByteArrayOutputStream instead of a FileOutputStream you can capture the output and then call toByteArray to get the data once it's finished writing.

As for serving it, when you get a request for the image, set the content type to "image/jpeg", set the content length to the length of the byte array, then write the bytes to the response's output stream.

0

精彩评论

暂无评论...
验证码 换一张
取 消