问题描述
这是我目前所拥有的,
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 读取图像文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)