0

I have written a small TCP client to retrieve various data. It works fine for text, but I have no clue how to implement image processing. At the moment, the incoming data is stored in an 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;
}

How can I create an Image or BufferedImage out of a GIF or JPEG stored in an ArrayList<String>? (Or am I completely in the dark and have to use different data structures?)

laserbrain
  • 985
  • 3
  • 10
  • 20

1 Answers1

1

Once you open an input stream from the server, create the image using 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
    }
}

For better efficiency, you might wrap in in a BufferedInputStream.

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521