图像Uri到文件

Mdl*_*dlc 3 android uri file bitmap

我有一个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);
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

(我已经看过这个答案了,但它找不到找到的文件 - /sf/answers/919378211/)

SDJ*_*tie 10

问题是,你被给予的Uri Images.Media.insertImage()本身并不是一个图像文件.它是Gallery中的数据库条目.因此,您需要做的是从该Uri读取数据并使用此答案将其写入外部存储中的新文件/sf/answers/606522381/

这不需要创建Bitmap,只需将链接到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();
}
Run Code Online (Sandbox Code Playgroud)