【问题标题】:Image URL to File Object文件对象的图像 URL
【发布时间】:2019-12-31 12:48:39
【问题描述】:

我正在尝试将此图像 url 转换为文件对象:

 https://graph.facebook.com/v4.0/10211842143528384/picture?height=200&width=200&migration_overrides=%7Boctober_2012%3Atrue%7D

此链接来自我登录后的 facebook 回复。

我用这个方法把这个图片的 url 转换成 File 对象:

  URL url = null;
        try {
            url = new URL(sharePreferences.getPreferencesProfilePicture());
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        File f = new File(url.getFile());
            Log.d("CHECKER",""+f.exists());
            Log.d("CHECKER",""+f.length());

但是当我检查它的长度时,它只是 0 并且文件存在是假的。

【问题讨论】:

  • 我很困惑?为什么我需要从 OKHTTP 下载二进制文件???
  • 您实际上并没有该文件,它正在返回它所在的位置,这就是您必须下载它的原因

标签: android file imageurl


【解决方案1】:

你有一个长度为 0 的文件,因为你只是用 url.getFile() 的结果名称创建它,url.getFile() 返回一个与获取的文件名对应的字符串。所以你最终得到一个名为图片的文件:
https://graph.facebook.com/v4.0/10211842143528384/picture?height=200&width=200&migration_overrides=%7Boctober_2012%3Atrue%7
但是内容呢?您必须将它们作为流从 Internet 下载并将该流馈送到文件中。使用纯 Java 有很多方法可以做到这一点。来自https://www.baeldung.com/java-download-file的基本复制粘贴

try (BufferedInputStream in = new BufferedInputStream(new URL(FILE_URL).openStream());
  FileOutputStream fileOutputStream new FileOutputStream(FILE_NAME)) {
    byte dataBuffer[] = new byte[1024];
    int bytesRead;
    while ((bytesRead = in.read(dataBuffer, 0, 1024)) != -1) {
        fileOutputStream.write(dataBuffer, 0, bytesRead);
    }
} catch (IOException e) {
    // handle exception
}

由于您使用的是 android,我强烈建议您使用功能齐全的网络库,例如 OkHttp3、Retrofit 或 Volley,但我认为您会更好地学习 Java 基础知识,然后跳转到上述库。

请记住,对于 android,您需要 INTERNET 权限才能访问互联网,然后如果您下载到外部存储上的文件,您还需要 EXTERNAL_STORAGE 权限。安卓代码片段:

try {
  URLConnection conection = url.openConnection();
  conection.connect();

  int lenghtOfFile = conection.getContentLength();

  // Read from the Network stream
  InputStream input = new BufferedInputStream(url.openStream());

  OutputStream output = new FileOutputStream(Environment
          .getExternalStorageDirectory().toString()
          + "/downloaded.png");

  byte data[] = new byte[1024];

  while ((count = input.read(data)) != -1) {
      total += count;
      // Feed the bytes read from the input stream into our output stream
      output.write(data, 0, count);
  }

  // Flushing the out stream.
  output.flush();

  // closing streams
  output.close();
  input.close();

} catch (Exception e) {
  Log.e("Error: ", e.getMessage());
}

这个 sn-p 做网络工作,所以你需要在后台线程上运行它。希望我的回答对您有所帮助,如果没有,请告诉我我还能为您做些什么。

【讨论】:

  • 我很抱歉,但我怎样才能得到文件对象呢?我很困惑对不起。
  • @netflixspotify 问题是你是否真的需要File - 为什么你认为你需要它?你不能只使用它的InputStream吗?
  • 为什么需要文件对象?反正下载后可以File file = new File(Environment.getExternalStorageDirectory().toString() + "/downloaded.png");
  • @pskink 我需要文件,因为我要把它发送到服务器先生
猜你喜欢
  • 1970-01-01
  • 2016-06-22
  • 2016-02-14
  • 2012-01-09
  • 1970-01-01
  • 2023-03-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多