【问题标题】:why is my image saved as all black with this code snippet?为什么我的图像使用此代码段保存为全黑?
【发布时间】:2016-04-01 07:55:12
【问题描述】:

我还在练习我的java,不太习惯Writers,bufferedWriters等。我有这个方法,它应该向服务器发出get请求,得到一个图像作为回报(文件名在标题中)并保存这个图片。除了它保存的图像被破坏为全黑(图像尺寸等是正确的)之外,这有效。任何人都可以帮助我解决可能导致此问题的原因,并提出解决方案吗?

private static void getAndSaveImage(String urlStem) throws Exception{
    URL url = new URL(urlStem);
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    con.setRequestMethod("GET");
    String fileName = "./" + con.getHeaderField("Content-Disposition").split("filename=")[1];
    BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
    BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));
    IOUtils.copy(reader, writer);
}

我目前正在调查这个线程的答案:Getting Image from URL (Java)

我尝试将此作为一种潜在的解决方案(我知道我会得到一个 .png 文件),但后来我发现图像文件是空的。

private static void getAndSaveImage(String urlStem) throws Exception {
    URL url = new URL(urlStem);
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    con.setRequestMethod("GET");
    BufferedImage image = ImageIO.read(con.getInputStream());
    String fileName = "./" + con.getHeaderField("Content-Disposition").split("filename=")[1];
    File file = new File(fileName);
    file.createNewFile();
    ImageIO.write(image, ".png" , file);
}

我用(从那个线程修改)解决了它:

public static void getAndSaveImage(String imageUrl) throws Exception {
    URL url = new URL(imageUrl);
    InputStream is = url.openStream();
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    con.setRequestMethod("GET");
    String fileName = "./" + con.getHeaderField("Content-Disposition").split("filename=")[1];
    OutputStream os = new FileOutputStream(fileName);
    byte[] b = new byte[2048];
    int length;

    while ((length = is.read(b)) != -1) {
        os.write(b, 0, length);
    }

    is.close();
    os.close();
}

但是在这个线程上的答案/建议更好。

我相信这将是建议的实施:

public static void saveImage(String imageUrl) throws Exception{
     URL url = new URL(imageUrl);
     HttpURLConnection con = (HttpURLConnection) url.openConnection();
     con.setRequestMethod("GET");
    String fileName = "./" + con.getHeaderField("Content-Disposition").split("filename=")[1]; 
    FileUtils.copyURLToFile(url, file);
} 

(遗憾的是,我似乎正在执行两个获取请求,以获取标题中的文件名信息和图像本身)

【问题讨论】:

    标签: java image


    【解决方案1】:

    改用 Commons FileUtils:

    org.apache.commons.io.FileUtils.copyURLToFile(URL, File)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-06-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-05
      • 2016-05-23
      • 1970-01-01
      • 2016-07-12
      相关资源
      最近更新 更多