图像Uri到文件

时间:2014-02-22 21:13:16

标签: android file bitmap uri

我有一个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是有效的。)

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

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

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

1 个答案:

答案 0 :(得分:9)

问题在于Images.Media.insertImage()给出的Uri本身并不是图像文件。它是Gallery中的数据库条目。因此,您需要做的是从该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();
}