通过 Java Socket 读取图像文件

2022-01-17 00:00:00 sockets http-headers http java

这是我目前所拥有的,

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.

My problem with my code is ImageIO.read() returns null.

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

When I print the content of ByteArrayOutputStream object what i get is header part

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;Öã....

followed with a empty line plus many lines with different characters such as Àã$sU,e6‡Í~áŸP;Öã….

我的问题又是 ImageIO.read() 函数返回 null.

Again my problem is ImageIO.read() function returns null.

提前致谢.

推荐答案

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

Why you don't want to use simple http URL to get image from host? I mean:

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

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

If you want to use plain socket you have to parse http response and extract data from the http reply manually: read/skip headers, read binary data and pass it to ImageIO.read (or seek stream to correct position and pass stream to ImageIO.read).

相关文章