Android 文件的图像Uri
我有一个图像Uri,使用以下方法检索:Android 文件的图像Uri,android,file,bitmap,uri,Android,File,Bitmap,Uri,我有一个图像Uri,使用以下方法检索: public Uri getImageUri(Context inContext, Bitmap inImage) { ByteArrayOutputStream bytes = new ByteArrayOutputStream(); inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes); String path = Images.Media.insertImage(inContex
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是有效的)
但是现在我想把这个图像URI保存到SD卡上的一个文件中。这更加困难,因为URI实际上并不指向SD卡或应用程序上的文件
我是否必须首先从URI创建位图,然后将位图保存到SD卡上,或者是否有更快的方法(最好是不需要首先转换为位图的方法)
(我已经看了这个答案,但它返回的是找不到文件-问题是,
Images.Media.insertImage()
提供给您的Uri本质上不是图像文件。它是库中的一个数据库条目。因此,您需要做的是从该Uri读取数据,并使用此答案将其写入外部存储器中的新文件
这不需要创建位图,只需将链接到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();
}
谢谢,但现在我必须将InputStream设置为byte[],这(正如谷歌建议的那样)需要使用像IOUtils这样的库或单独的返回方法IOUtils只是一个方便的库。。。我会更新我的答案非常感谢你的时间!我还得到了一个异常:java.io.IOException:open failed:enoint(没有这样的文件或目录)在file.createnewfile()行中,什么是bytesRead
?它是一个int
值,我忘了在我的示例中声明,我将添加它。它告诉您在read()
方法中实际读取了多少字节