java 在java中读取和存储.bmp文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13110159/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 11:31:23  来源:igfitidea点击:

reading and storing a .bmp file in java

javabitmapfile-io

提问by Q Zhao-Liu

I'm am trying to read a .bmp file called circle1.bmp. It is in a package that I have imported into the following file.

我正在尝试读取一个名为 .bmp 的文件circle1.bmp。它位于我已导入到以下文件中的包中。

So far I have the following code, but when I run the following code I get:

到目前为止,我有以下代码,但是当我运行以下代码时,我得到:

javax.imageio.llOException: Can't read input file!

javax.imageio.llOException:无法读取输入文件!

public void setUp() throws IOException
{
    BufferedImage image = ImageIO.read(new File("circle1.bmp"));
    byte[][] greenInputData = new byte[30][40];

    for (int x = 0; x < inputData.length; x++)
    {
        for (int y = 0; y < inputData[x].length; y++)
        {
            int color = image.getRGB(x, y);
            //alpha[x][y] = (byte)(color>>24);
            //red[x][y] = (byte)(color>>16);
            greenInputData[x][y] = (byte)(color>>8);
            //blue[x][y] = (byte)(color);
        }
    }
    this.inputData = greenInputData;

    System.out.println(this.inputData);
}

采纳答案by Werner Kvalem Vester?s

You should try something like

你应该尝试类似的东西

image = ImageIO.read(getClass().getResourceAsStream("path/to/your/file.bmp"));

回答by Sasi Kathimanda

Likely your image's file path isn't correct relative to the user directory. To find out where Java is starting to look, where the user directory is, place something like this line of code somewhere in your program:

相对于用户目录,您的图像文件路径可能不正确。要找出 Java 开始查找的位置、用户目录的位置,请在程序中的某处放置类似以下代码行的内容:

System.out.println(System.getProperty("user.dir"));

Perhaps you'd be better off getting the image as an InputStream obtained from a resource and not as a file. e.g.,

也许您最好将图像作为从资源获得的 InputStream 而不是作为文件来获取。例如,

image = ImageIO.read(getClass().getResourceAsStream("circle1.bmp")); //prefered

or

或者

image = ImageIO.read(getClass().getResource("circle1.bmp"));

This will look for the image at the path given relative to the location of the class files, and in fact this is what you must do if your image is located in your jar file.

这将在相对于类文件位置的给定路径中查找图像,实际上,如果图像位于 jar 文件中,则必须执行此操作。