【问题标题】:Read Image From Web And Write to File in Java [duplicate]从 Web 读取图像并用 Java 写入文件 [重复]
【发布时间】:2018-01-13 21:12:11
【问题描述】:

我正在尝试从网页中获取图像并写入文件,但最后我的照片查看器无法识别图片文件并且无法打开它(该文件无法读取)。

这是我的代码:

URL urlpic = new URL("https://static.asset.aparat.com/lp/16107806-6200-m.jpg");//示例图片url HttpURLConnection connectionToPicFile=(HttpURLConnection)urlpic.openConnection(); BufferedReader buffPic=new BufferedReader(new InputStreamReader(connectionToPicFile.getInputStream()));

String pic = "";
String alldatapic = "";
while((pic=buffPic.readLine()) != null)
{
    alldatapic += pic;
}

try
{
    FileOutputStream fout = new FileOutputStream("D://pic.jpg");//where i want the file to be saved
    byte[] b = alldatapic.getBytes();
    fout.write(b);
    fout.close();
}
catch(Exception ex)
{
    System.out.println(ex.toString()+"   "+ex.getMessage());
}

【问题讨论】:

标签: java io bufferedreader


【解决方案1】:

你应该使用这样的东西:

BufferedImage image = null;
        try {

            URL url = new URL("https://static.asset.aparat.com/lp/16107806-6200-m.jpg");
            image = ImageIO.read(url);

            ImageIO.write(image, "jpg", new File("E:\\out.jpg"));


        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("Done");
    }

在 Windows 10 上,您不能使用根路径 (C:\) 来存储新文件。

【讨论】:

  • 感谢您的回答。但是,有没有办法通过使用 bufferedwriter 编写?
  • 简答:否
  • 不需要ImageIO,它将使用新参数写入文件。只需copy the URL
猜你喜欢
  • 2015-08-04
  • 1970-01-01
  • 2019-07-27
  • 2012-05-27
  • 2011-12-18
  • 2010-11-29
  • 2012-12-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多