简体   繁体   English

Java ImageIO声明图像

[英]Java ImageIO claims image

I'm working on an application which reloads an image every once in a while. 我正在开发一个不时刷新图像的应用程序。 I did that so I could make changes on the go externally. 我这样做是为了可以在外部进行更改。 I'm using ImageIO.read(path) to read the image file. 我正在使用ImageIO.read(path)读取图像文件。

Now when I want to change the image with my paint.NET and try to save(overwrite) the image, paint.NET throws an IOException. 现在,当我想用​​我的paint.NET更改图像并尝试保存(覆盖)图像时,paint.NET会引发IOException。 This is probably because ImageIO just claims the image to be his while the process is running. 这可能是因为ImageIO在进程运行时只是声称该映像是他的。 But that's what I think. 但这就是我的想法。

The Code is here: 代码在这里:

public int width, height;
public int[] pixels;

public Sprite(String ref) {
    try {
        BufferedImage image = ImageIO.read(new FileInputStream(ref));
        width = image.getWidth();
        height = image.getHeight();
        pixels = new int[width * height];
        pixels = image.getRGB(0, 0, width, height, pixels, 0, width);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Anyone knows how to fix this? 有人知道如何解决这个问题吗?

Thanks! 谢谢!

On Windows (I assume you're on Windows, as you mention you use Paint.NET), holding onto a file is particularly problematic, as it will prevent other applications from writing to that same file. 在Windows上(假设您使用的是Paint.NET,我假设您在Windows上),将文件保存起来特别成问题,因为它将阻止其他应用程序写入该文件。 Most likely, this is the problem you encounter. 这很可能是您遇到的问题。

When you open a stream, like you do here: 打开流时,就像在这里一样:

new FileInputStream(ref);

You acquire a native file pointer. 您获得一个本机文件指针。 It is your responsibility to close it again after use, to release the file pointer. 您有责任在使用后再次将其关闭,以释放文件指针。 Now, ImageIO.read(InputStream) should close the stream for you, but in certain cases and certain versions of Java, there has been bugs related to this. 现在, ImageIO.read(InputStream) 应该为您关闭流,但是在某些情况下和某些Java版本中,存在与此相关的错误。 If the stream is not properly closed, the Java process will hold onto this file pointer as a worst case until the Java process terminates. 如果未正确关闭流,则在最坏的情况下,Java进程将保留此文件指针,直到Java进程终止。

The good news, is that if you simply change your code to: 好消息是,如果您只是将代码更改为:

BufferedImage image = ImageIO.read(new File(ref));

Then ImageIO will always take care of the opening and closing of the stream. 然后ImageIO将始终照顾流的打开和关闭。

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

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