2009-12-19 147 views
16

我有一個.gif文件在資產文件夾內像這樣assets/Files/android.gif。當我嘗試打開它拋出一個異常文件第二行從資產文件夾中打開一個文件在android

AssetManager mngr=getAssets(); 
InputStream is2=mngr.open("Files/android.gif"); 

那麼,這是我試圖打開一個圖像文件,儘管相同的代碼工作,如果我試圖打開一個文本文件? 這裏有什麼問題。

回答

30

這些線路perfectly--

InputStream assetInStream=null; 

try { 
    assetInStream=getAssets().open("icon.png"); 
    Bitmap bit=BitmapFactory.decodeStream(assetInStream); 
    img.setImageBitmap(bit); 
} catch (IOException e) { 
    e.printStackTrace(); 
} finally { 
    if(assetInStream!=null) 
    assetInStream.close(); 
} 

工作。如果你的形象是非常大的,那麼你應該把它解碼成位圖前縮放圖像。 See How to display large image efficiently

+3

AFIK流應在使用後關閉 – ruX 2012-02-19 07:58:32

+0

@ruX:是正確指出的問題 – Sameer 2012-06-14 10:58:15

1

,如果事情已經改變或沒有,但我在的Android 1.1的應用程序,打開圖標,然後在視圖中顯示出來,我做到了,像這樣不知道:

BufferedInputStream buf = new BufferedInputStream(mContext.openFileInput(value)); 
Bitmap bitmap = BitmapFactory.decodeStream(buf); 
1

我相信首選這樣做的方法是將您的圖像放在res/drawable目錄中。然後你可以得到像這樣的Drawable:

Drawable d = Resources.getSystem().getDrawable(R.drawable.android); 
4

我懷疑你正在接受關於未處理的異常類型IOException的投訴。如果是這種情況,您需要將調用mgr.open放入try-catch塊來處理檢索InputStream對象時可能發生的異常。

AssetManager mngr = getAssets(); 
try { 
    InputStream is2 = mngr.open("Files/android.gif"); 
} catch (final IOException e) { 
    e.printStackTrace(); 
} 
相關問題