【问题标题】:How to save Photos?如何保存照片?
【发布时间】:2018-08-20 10:27:01
【问题描述】:

我是 Android 编程新手,还没有找到解决问题的好方法。在我的应用程序中,用户可以从他们的图库中选择照片,然后在 Cardview 布局中用于用户可以自己创建的应用程序中的不同类别。到目前为止,我可以获取所选照片的​​ Uri 并显示它。但是如何将照片保存到我的应用程序以确保它始终存在,即使它已从图库中删除?

【问题讨论】:

  • 只需复制文件并将其保存到您想要的位置。 Copy fileStorage
  • 但我最好把它保存在哪里?
  • 照片被删除后显示的目的是什么?将它们保存在私有/外部存储中可能就足够了。

标签: android uri photos saving-data


【解决方案1】:

参考:How to make a copy of a file in android?

要复制文件并将其保存到目标路径,您可以使用以下方法。

public static void copy(File src, File dst) throws IOException {
    InputStream in = new FileInputStream(src);
    try {
        OutputStream out = new FileOutputStream(dst);
        try {
            // Transfer bytes from in to out
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
        } finally {
            out.close();
        }
    } finally {
        in.close();
    }
}

在 API 19+ 上,您可以使用 Java 自动资源管理: 公共静态无效副本(文件 src,文件 dst)抛出 IOException { t

ry (InputStream in = new FileInputStream(src)) {
        try (OutputStream out = new FileOutputStream(dst)) {
            // Transfer bytes from in to out
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-29
    • 1970-01-01
    • 2013-08-16
    • 2010-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-10
    相关资源
    最近更新 更多