使用 Java 从文件中读取图像,并将其保存到不同的文件中

Using Java to read image from file, and saving it to a different file

我正在尝试执行上述操作,但每次都会出现以下错误java.io.FileNotFoundException: file:\C:\Users\User\Desktop\Scrap\main\out\production\resources\ProfilePic\xas.png (The filename, directory name, or volume label syntax is incorrect)

这是我用来执行此操作的函数

  private URL url = this.getClass().getResource("/ProfilePic");
  public final String PICTURE_DIRECTORY  = url.toString();


 public String createNewPicture (String path, String newPictureName) {
    int width = 12;
    int height = 12;
    BufferedImage bf = null;
    File f = null;
    String dst = PICTURE_DIRECTORY +"/"+newPictureName+".png";
    try{
        f = new File("F://a.jpg");
        bf = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);

        bf = ImageIO.read(f);
        System.out.println("read file successfully");


    } catch (Exception e) {
        System.out.println(e.getMessage());
    }

    try {
        dst = PICTURE_DIRECTORY +"/"+newPictureName+".png";
        new File (PICTURE_DIRECTORY, newPictureName+".png");
        f = new File(dst);
       ImageIO.write(bf, "png", f);
        //System.out.println("asaas " +dst);
    }
    catch (Exception e) {
        System.out.println(e.getMessage());
    }

    return dst;
}

有人可以帮助我吗?花了几个小时试图解决这个问题但卡住了。谢谢!

您需要的信息在错误信息中找到:

java.io.FileNotFoundException: file:\C:\Users\User\Desktop\Scrap\main\out\production\resources\ProfilePic\xas.png (The filename, directory name, or volume label syntax is incorrect)

您的代码中的问题在此处:

private URL url = this.getClass().getResource("/ProfilePic");
public final String PICTURE_DIRECTORY  = url.toString();

A URL 包含一个协议,在您的例子中是 "file"。 URL class' toString() 只是 returns 完整的 URL, 包括协议 。 您现在有包含 "file:/C:/..." 的变量 PICTURE_DIRECTORY。这不是任何 Windows OS 上的有效路径。

如果你真的想写入资源(不推荐),你可以这样做:

public final String PICTURE_DIRECTORY  = toFile(url).getAbsolutePath(); 

static private File toFile(final URL url) {
    try {
        return new File(url.toURI());
    }
    catch (URISyntaxException e) {
        throw new IllegalArgumentException(e);
    }
}

但请注意,Class..getResource(..) 返回的资源并不总是文件。它也可以是 JAR 中的一个条目(您不能写入,就像写入文件一样)。

更好的方法可能是使用相对于用户主目录或其他配置目录的目录。

最后,正如我在评论中提到的,使用 ImageIO 复制(图像)文件通常是错误的解决方案。相反,使用 Files.copy(...),如 Copying a File or Directory 教程中所述。