图片URI到文件 [英] 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);
}
这工作得惊人用于需要一个图像URI等意图(所以我确切地知道URI是有效的)。
This works just amazing for Intents that require an Image URI, etc (so I know for sure the URI is valid).
但现在我想这个图像URI保存到SD卡中的文件。这是比较困难的,因为URI并没有真正在对SD卡或应用程序的文件点。
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的位图,然后保存位图上的SD卡或者是有一个更快的方式(preferable一个不需要转换为位图在前)。
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).
(我有一个看看这个答案,但它返回未找到文件 - <一个href=\"http://stackoverflow.com/a/13133974/1683141\">http://stackoverflow.com/a/13133974/1683141)
(I've had a look at this answer, but it returns file not found - http://stackoverflow.com/a/13133974/1683141)
推荐答案
的问题是,你被给出的乌里Images.Media.insertImage()
ISN T图像文件,本身。这是在库数据库条目。所以,你需要做的就是从开放的,并使用这个答案 HTTP读取数据的内容: //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 http://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.
您可以用code像得到使用InputStream中的数据:
You can get the data using an InputStream using code like:
中的InputStream = getContentResolver()openInputStream(imgUri);
这是完全未经测试code,但你应该能够做这样的事:
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屋!