我编写了一个小型TCP客户端来检索各种数据。它适用于文本,但我不知道如何实现图像处理。目前,传入的数据存储在ArrayList<String>
:
public ArrayList<String> sendSelector(String selector, String host, int port) throws IOException {
socket = new Socket(host, port);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out.println(encodePercent(selector) + CRLF);
ArrayList<String> lines = new ArrayList();
String line;
while ((line = in.readLine()) != null) {
if (line.equals("."))
break;
lines.add(line);
}
out.close();
in.close();
socket.close();
return lines;
}
如何从Image
中存储的GIF或JPEG中创建BufferedImage
或ArrayList<String>
? (或者我完全在黑暗中并且必须使用不同的数据结构?)
答案 0 :(得分:1)
从服务器打开输入流后,使用ImageIO.read(InputStream)
创建图像:
public BufferedImage sendSelector(String selector, String host, int port) throws IOException {
socket = new Socket(host, port);
try {
out = new PrintWriter(socket.getOutputStream(), true);
out.println(encodePercent(selector) + CRLF);
in = socket.getInputStream();
return ImageIO.read(in);
} finally {
socket.close(); // closes in and out as well
}
}
为了提高效率,您可以将in
包裹在BufferedInputStream
。