图像 Uri 到文件 [英] Image Uri to File
问题描述
我有一个图像 Uri,使用以下方法检索:
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);
}
这对于需要图像 URI 等的 Intent 非常有用(所以我确定 URI 是有效的).
This works just amazing for Intents that require an Image URI, etc (so I know for sure the URI is valid).
但现在我想将此图像 URI 保存到 SDCARD 上的文件中.这更困难,因为 URI 并不真正指向 SDCARD 或应用程序上的文件.
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.
我是否必须先从 URI 创建位图,然后将位图保存在 SDCARD 上,或者有更快捷的方法(最好是不需要先转换为位图的方法).
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).
(我看过这个答案,但它返回找不到文件 - https://stackoverflow.com/a/13133974/1683141)
(I've had a look at this answer, but it returns file not found - https://stackoverflow.com/a/13133974/1683141)
推荐答案
问题是 Images.Media.insertImage()
给你的 Uri 不是图像文件,本身.它指向图库中的数据库条目.因此,您需要做的是从该 Uri 中读取数据,并使用此答案将其写入外部存储中的新文件 https://stackoverflow.com/a/8664605/772095
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
这不需要创建位图,只需将链接到 Uri 的数据复制到一个新文件中即可.
This doesn't require creating a Bitmap, just duplicating the data linked to the Uri into a new file.
您可以使用以下代码使用 InputStream 获取数据:
You can get the data using an InputStream using code like:
InputStream in = getContentResolver().openInputStream(imgUri);
这是完全未经测试的代码,但您应该能够执行以下操作:
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();
}
这篇关于图像 Uri 到文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!