【问题标题】:Image Uri to File图像 Uri 到文件
【发布时间】:2014-02-22 21:13:16
【问题描述】:

我有一个 Image Uri,使用以下方法检索到:

public Uri getImageUri(Context inContext, Bitmap inImage) {
  ByteArrayOutputStream bytes = new ByteArrayOutputStream();
  inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
  String path = Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
  return Uri.parse(path);
}

这对于需要图像 URI 等的 Intent 非常有效(所以我确定 URI 是有效的)。

但现在我想将此图像 URI 保存到 SDCARD 上的文件中。这更加困难,因为 URI 并不真正指向 SDCARD 或应用程序上的文件。

我必须先从 URI 创建位图,然后将位图保存在 SDCARD 上还是有更快的方法(最好不需要先转换为位图)。

(我看过这个答案,但它返回文件未找到 - https://stackoverflow.com/a/13133974/1683141

【问题讨论】:

    标签: android file bitmap uri


    【解决方案1】:

    问题在于Images.Media.insertImage() 提供的 Uri 本身并不是图像文件。它指向图库中的数据库条目。因此,您需要做的是从该 Uri 读取数据并使用此答案 https://stackoverflow.com/a/8664605/772095

    将其写入外部存储中的新文件

    这不需要创建位图,只需将链接到 Uri 的数据复制到一个新文件中即可。

    您可以使用以下代码使用 InputStream 获取数据:

    InputStream in = getContentResolver().openInputStream(imgUri);

    更新

    这是完全未经测试的代码,但您应该能够执行以下操作:

    Uri imgUri = getImageUri(this, bitmap);  // I'll assume this is a Context and bitmap is a Bitmap
    
    final int chunkSize = 1024;  // We'll read in one kB at a time
    byte[] imageData = new byte[chunkSize];
    
    try {
        InputStream in = getContentResolver().openInputStream(imgUri);
        OutputStream out = new FileOutputStream(file);  // I'm assuming you already have the File object for where you're writing to
    
        int bytesRead;
        while ((bytesRead = in.read(imageData)) > 0) {
            out.write(Arrays.copyOfRange(imageData, 0, Math.max(0, bytesRead)));
        }
    
    } catch (Exception ex) {
        Log.e("Something went wrong.", ex);
    } finally {
        in.close();
        out.close();
    }
    

    【讨论】:

    • 谢谢,但现在我必须将 InputStream 设为 byte[],这(正如谷歌快速建议的那样)需要使用 IOUtils 之类的库或单独的返回方法
    • IOUtils 只是一个便利库...我会更新我的答案
    • 非常感谢您的宝贵时间!我也遇到了一个异常: java.io.IOException: open failed: ENOENT (No such file or directory) 在 File.createnewfile()
    • 嗨,bytesRead 是什么?
    • 这是我在示例中忘记声明的int 值,我将添加它。它告诉您在read() 方法中实际读取了多少字节
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-30
    • 2020-07-26
    • 2011-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多