简体   繁体   English

使用Java中的FileInputStream读取图像

[英]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. 我正在尝试使用fileInputStream读入图像并写出以生成另一个图像。 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: 使用超级编辑后,这是我从前4个字节得到的结果:
original image:42 4D 7A 95 原始图像:42 4D 7A 95
new image:42 4D 7A 3F 新图像:42 4D 7A 3F
It seems that every byte which its MSB is 1 has been changed to 3F . 看来其MSB为1的每个字节都已更改为3F I know every data type in Java is signed, and also I already have tried to and 0xff to every byte. 我知道Java中的每种数据类型都是经过签名的,而且我已经尝试过将0xff分配给每个字节。

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. 您需要写入4字节的int。 Not truncate the int to byte 不将int截断为字节

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. 但是,如果要更改像素并重写新图像,则需要imageio(或其他某种机制)来写入图像。

-- -

OutputStreamWriter writes characters; OutputStreamWriter写入字符; why dont you use the equivalent: 为什么不使用等效项:

FileOutputStream: you can write the bytes as you read them. FileOutputStream:您可以在读取字节时写入它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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