到目前为止,这就是我所拥有的,
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回复中提取数据:读/跳过 header ,读取二进制数据并将其传递给
ImageIO.read
(或查找流以纠正位置并将流传递给ImageIO.read
)。