Image Uri to File

旧街凉风 提交于 2020-01-20 05:21:52

问题


I've got an Image Uri, retrieved using the following:

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);
}

This works just amazing for Intents that require an Image URI, etc (so I know for sure the URI is valid).

But now I want to save this Image URI to a file on the SDCARD. This is more difficult because the URI does not really point at a file on the SDCARD or the app.

Will I have to create a bitmap from the URI first, and then save the Bitmap on the SDCARD or is there a quicker way (preferable one that does not require the conversion to a bitmap first).

(I've had a look at this answer, but it returns file not found - https://stackoverflow.com/a/13133974/1683141)


回答1:


The problem is that the Uri you've been given by Images.Media.insertImage() isn't to an image file, per se. It is to a database entry in the Gallery. So what you need to do is read the data from that Uri and write it out to a new file in the external storage using this answer https://stackoverflow.com/a/8664605/772095

This doesn't require creating a Bitmap, just duplicating the data linked to the Uri into a new file.

You can get the data using an InputStream using code like:

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

Update

This is completely untested code, but you should be able to do something like this:

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();
}


来源:https://stackoverflow.com/questions/21960650/image-uri-to-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!