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 读取图像文件
基础教程推荐
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 降序排序:Java Map 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01