通过Java Socket读取映像文件

这是我到目前为止,

Socket clientSocket = new Socket(HOST, PORT); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); InputStream is = socket.getInputStream(); byte[] byteChunk = new byte[1024]; int c = is.read(byteChunk); while (c != -1){ buffer.write(byteChunk, 0, c); c = is.read(byteChunk); } BufferedImage bufferedImage = ImageIO.read(new ByteArrayInputStream(buffer.toByteArray())); 

我的代码问题是ImageIO.read()返回null。

当我打印ByteArrayOutputStream对象的内容时,我得到的是标题部分

 HTTP/1.1 200 OK Date: Fri, 30 Dec 2011 11:34:19 GMT Server: Apache/2.2.3 (Debian) ........... Last-Modified: Tue, 20 Dec 2011 19:12:23 GMT ETag: "502812-490e-4b48ad8d273c0" Accept-Ranges: bytes Content-Length: 18702 Connection: close Content-Type: image/jpeg 

接着是一个空行加上许多不同字符的行,如Àã$sU,e6‡Í~áŸP;Öã…

我的问题再次是ImageIO.read()函数返回null。

提前致谢。

为什么你不想使用简单的http URL从主机获取图像? 我的意思是:

 URL imageURL = new URL("http://host:port/address"); BufferedImage bufferedImage = ImageIO.read(imageURL); 

如果要使用普通套接字,则必须解析http响应并手动从http回复中提取数据:读取/跳过标头,读取二进制数据并将其传递给ImageIO.read (或寻找流以纠正位置并将流传递给ImageIO.read )。