3

我正在尝试使用Image.IO.Write();保存图像 我基本上已经从这里复制了标准代码,用 lwjgl 截屏。我唯一做的就是使用现有目录作为保存路径初始化文件。

当我尝试保存图像时,FileNotFoundException会被抛出。

    glReadBuffer(GL_FRONT);
    int width  = Display.getDisplayMode().getWidth();
    int height = Display.getDisplayMode().getHeight();
    int bpp = 4; // Assuming a 32-bit display with a byte each for red, green, blue, and alpha.
    ByteBuffer buffer = BufferUtils.createByteBuffer(width * height * bpp);
    glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, buffer);

    File file = new File("res/screenshots/ss_" + Sys.getTime() + ".png"); // The file to save to.
    String format = "PNG"; // Example: "PNG" or "JPG"
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

    for(int x = 0; x < width; x++)
        for(int y = 0; y < height; y++)
        {
            int i = (x + (width * y)) * bpp;
            int r = buffer.get(i) & 0xFF;
            int g = buffer.get(i + 1) & 0xFF;
            int b = buffer.get(i + 2) & 0xFF;
            image.setRGB(x, height - (y + 1), (0xFF << 24) | (r << 16) | (g << 8) | b);
        }

    try {
        ImageIO.write(image, format, file);
    } catch (IOException e) { e.printStackTrace(); }

堆栈跟踪:

java.io.FileNotFoundException: res\screenshots\ss_91733792.png (The system cannot find the path specified)
    at java.io.RandomAccessFile.open(Native Method)
    at java.io.RandomAccessFile.<init>(Unknown Source)
    at javax.imageio.stream.FileImageOutputStream.<init>(Unknown Source)
    at com.sun.imageio.spi.FileImageOutputStreamSpi.createOutputStreamInstance(Unknown Source)
    at javax.imageio.ImageIO.createImageOutputStream(Unknown Source)
    at javax.imageio.ImageIO.write(Unknown Source)
    at com.va.util.Extras.takeScreenShot(Extras.java:46)
    at com.va.core.Engine.start(Engine.java:117)
    at Main.main(Main.java:26)
Exception in thread "main" java.lang.NullPointerException
    at javax.imageio.ImageIO.write(Unknown Source)
    at com.va.util.Extras.takeScreenShot(Extras.java:46)
    at com.va.core.Engine.start(Engine.java:117)
    at Main.main(Main.java:26)
4

2 回答 2

3

我假设“/res/screenshots”存在并且是可写的,对吗?

我猜您程序的当前目录可能与您期望的不同。

出于调试目的,请添加以下两行(或等效行):

  String currentDir = new File(".").getAbsolutePath();
  System.out.println ("Current directory: " + currentDir);

如果“res/screenshots”不在“currentDirectory”下,则更改代码中的相对路径。

  // EXAMPLE:
  File file = new File("../..res/screenshots/ss_" + Sys.getTime() + ".png"); 
于 2012-06-21T16:10:05.937 回答
1

您链接到的代码没有显示文件是如何创建的,而是将其留给程序员。

您正在做的可能只是创建一个新File对象

File img = new File("path/to/file.jpg");

您的问题是,该path/to文件夹不存在,并ImageIO抛出FileNotFoundException.

要完成这项工作,请使用

img.getParent().mkdirs();

在你通过imgto之前ImageIO。这样可以确保文件的完整路径是可访问的。正如这篇文章的评论中所述,文件本身不必存在,但 id 的路径却存在。

于 2012-06-21T16:00:26.917 回答