简体   繁体   中英

Read an image using FileInputStream in Java

I am trying to use fileInputStream to read an image in and write out to produce another image. I want to read pixels in and then change pixels to get an left-right flip image. However, now I only read image in and write it directly out, I get something wrong. After using ultra edit, here is what i get from first 4 bytes:
original image:42 4D 7A 95
new image:42 4D 7A 3F
It seems that every byte which its MSB is 1 has been changed to 3F . I know every data type in Java is signed, and also I already have tried to and 0xff to every byte.

public static void imageOut() {
   try {
        FileInputStream in = new FileInputStream(new File(getPath()));
        int[] temp = new int[fSize];
        int i = 0;

        while (in.available() > 0) {
            temp[i] = in.read();
            i++;
        }

        OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(getOutputPath()));
        for (int j = 0; j < temp.length; j++) {
            out.write(((byte)temp[j]));
        }

        out.flush();
        out.close();

    } catch (IOException e) {
        e.printStackTrace();
    }
}

Yes because you are writing bytes

out.write(((byte)temp[j]))

you need to write int which is 4 bytes. Not truncate the int to byte

out.write(temp[j])

Eventually this is not the way to write the image - this will reproduce the file so its ok for this application (just copy a file nothing more). But if you want to change the pixels and rewrite a new image you will need imageio (or some other mechanism) to write images.

--

OutputStreamWriter writes characters; why dont you use the equivalent:

FileOutputStream: you can write the bytes as you read them.

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