Read Image File Through Java Socket(通过 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.
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).
这篇关于通过 Java Socket 读取图像文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:通过 Java Socket 读取图像文件
基础教程推荐
- 修改 void 函数的输入参数,然后读取 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
