![](/img/trans.png)
[英]FileNotFoundException when trying to download a image from web
[英]Android : FileNotFoundException when trying to get an image from Uri
我正在嘗試獲取圖像的寬度和高度,以便在顯示之前調整它的大小,以防它太大。 我的方法接收圖像的 uri,但在嘗試使用 BitmapFactory 對其進行解碼時,我總是收到 FileNotFoundException。
這是我的代碼示例:
Uri myUri;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(new File(myUri.getPath()).getAbsolutePath(), options);
int imageHeight = options.outHeight;
int imageWidth = options.outWidth;
解碼文件返回在這里拋出一個 FileNotFoundException。 但是,我仍然可以使用 uri 顯示圖像,而無需使用位圖工廠:
Uri myUri;
Bitmap myBitmap = MediaStore.Images.Media.getBitmap(context.getContentResolver(), myUri);
此代碼的問題在於,在使用大圖像時,返回的位圖可能會導致 OutofMemoryError。
當我調試我的 Uri 時,我得到了這個:
content://com.android.providers.media.documents/document/image%3A20472
更新 || 這是工作代碼
Uri myUri;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
// This is the part that changed
InputStream inputStream = context.getApplicationContext().getContentResolver().openInputStream(myUri);
BitmapFactory.decodeStream(inputStream,new Rect(),options);
int imageHeight = options.outHeight;
int imageWidth = options.outWidth;
當然,所有這些都被 try/catch 包圍。
在玩了一段時間之后,我認為問題可能是圖像文件確實不存在。
如果您嘗試訪問計算機上的本地文件,該文件將不會位於應用實際運行的 Android 沙箱中。 您需要將它作為資源添加到應用程序中,然后作為資源而不是文件訪問它。
如果您嘗試訪問網絡圖像,則需要先下載它。 Web 圖像“ http://example.com/example.jpg ”的 AbsolutePath 將是“/example.jpg”,當您嘗試打開它時,這對您沒有多大好處。
使用decodeStream
而不是decodeFile
。
使用getContentResolver().openInputStream(myUri)
打開流。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.