Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

android - Image Uri to File

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)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...