简体   繁体   中英

Is it possible to read images without ImageIO?

I am trying to read an image and deliver it through a Java socket. But there are some bits that does not fit. When viewing in a diff tool I realized that all numbers bigger than 127 were truncated.

So I wanted to just convert it to a char[] array and return it instead. Now I'm getting a complette different image, perhaps due to char's size.

        try (PrintWriter out = new PrintWriter(this.socket.getOutputStream(), true);
                BufferedInputStream in = new BufferedInputStream(new FileInputStream(filename), BUFSIZ)) {
            byte[] buffer = new byte[BUFSIZ];
            while (in.read(buffer) != -1) {
                response.append(new String(buffer));
                out.print(response.toString());
                response.setLength(0);
            }
        } catch (IOException e) {
            System.err.println(e.getMessage());
        }

This is my reading and delivering code.

I've read many times to use ImageIO but I want to do it without, since I don't know whether it's an image or not. (And what about other file types like executables?)

So, is there any way to convert it to something like an unsigned byte that'll be delivered correctly on the client? Do I have to use something different than read() to achieve that?

Writers are for character data. Use the OutputStream. And you're making the usual mistake of assuming that read() filled the buffer.

The following loop will copy anything correctly. Memorize it.

int count;
byte[] buffer = new byte[8192];
while ((count = in.read(buffer)) > 0)
{
    out.write(buffer, 0, count);
}

Repeat after me: a char is not a byte and it's not a code point.

Repeat after me: a Writer is not an OutputStream .

    try (OutputStream out = this.socket.getOutputStream();
         BufferedInputStream in = new BufferedInputStream(new FileInputStream(filename), BUFSIZ)) {
        byte[] buffer = new byte[BUFSIZ];
        int len;
        while ((len = in.read(buffer))) != -1) {
            out.write(buffer, 0, len);
        }
    } catch (IOException e) {
        System.err.println(e.getMessage());
    }

(this is from memory, check the args for write()).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM