2011-12-14 8 views
30

मुझे बिटमैप और संपत्ति से ध्वनि प्राप्त करने की आवश्यकता है। मैं इस तरह से करने की कोशिश:एंड्रॉइड बिटमैप या परिसंपत्तियों से ध्वनि प्राप्त करें

BitmapFactory.decodeFile("file:///android_asset/Files/Numbers/l1.png"); 

और इस तरह:

getBitmapFromAsset("Files/Numbers/l1.png"); 
    private Bitmap getBitmapFromAsset(String strName) { 
     AssetManager assetManager = getAssets(); 
     InputStream istr = null; 
     try { 
      istr = assetManager.open(strName); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     Bitmap bitmap = BitmapFactory.decodeStream(istr); 
     return bitmap; 
    } 

लेकिन मैं सिर्फ मुक्त स्थान है, छवि मिलता है।

यह कैसे करें?

उत्तर

98
public static Bitmap getBitmapFromAsset(Context context, String filePath) { 
    AssetManager assetManager = context.getAssets(); 

    InputStream istr; 
    Bitmap bitmap = null; 
    try { 
     istr = assetManager.open(filePath); 
     bitmap = BitmapFactory.decodeStream(istr); 
    } catch (IOException e) { 
     // handle exception 
    } 

    return bitmap; 
} 

पथ बस आपकी फ़ाइल का नाम fx bitmap.png है।/तो इसकी बिटमैप अगर आप उप-फ़ोल्डर बिटमैप का उपयोग/bitmap.png

+0

यह सही तरीका है। लेकिन मैं केवल खाली जगह देखता हूं तस्वीर नहीं .. मैंने क्या गलत किया? – Val

+0

अपनी तस्वीर की जांच करें ... डीबग और चरण के माध्यम से उपयोग करने का प्रयास करें। अधिक जानकारी दें, जहां आप चित्र कहां रखा गया है और इसे क्या कहा जाता है। – Warpzit

+0

यदि आप उपफोल्डर – Warpzit

10

इस कोड को अपनी कार्यशील

try { 
    InputStream bitmap=getAssets().open("icon.png"); 
    Bitmap bit=BitmapFactory.decodeStream(bitmap); 
    img.setImageBitmap(bit); 
} catch (IOException e1) { 
    // TODO Auto-generated catch block 
    e1.printStackTrace(); 
} 

अद्यतन

बिटमैप हम अधिक बार स्मृति अतिप्रवाह अपवाद के साथ मिलने डिकोडिंग जबकि उपयोग करता है, तो छवि का आकार बहुत बड़ा है। तो लेख पढ़ने How to display Image efficiently आपकी मदद करेगा।

6

स्वीकृत उत्तर InputStream को कभी बंद नहीं करता है। संपत्ति फ़ोल्डर में Bitmap प्राप्त करने के लिए यहां एक उपयोगिता विधि है:

/** 
* Retrieve a bitmap from assets. 
* 
* @param mgr 
*   The {@link AssetManager} obtained via {@link Context#getAssets()} 
* @param path 
*   The path to the asset. 
* @return The {@link Bitmap} or {@code null} if we failed to decode the file. 
*/ 
public static Bitmap getBitmapFromAsset(AssetManager mgr, String path) { 
    InputStream is = null; 
    Bitmap bitmap = null; 
    try { 
     is = mgr.open(path); 
     bitmap = BitmapFactory.decodeStream(is); 
    } catch (final IOException e) { 
     bitmap = null; 
    } finally { 
     if (is != null) { 
      try { 
       is.close(); 
      } catch (IOException ignored) { 
      } 
     } 
    } 
    return bitmap; 
} 
+0

यह स्वीकार्य उत्तर होना चाहिए! आप स्ट्रीम को बंद नहीं करना चाहते हैं क्योंकि बाद में आप जिस प्रकार का अपवाद प्राप्त कर सकते हैं वह मूल अपवाद होगा, जिसका अर्थ है कि आप इसे पकड़ने में सक्षम नहीं होंगे :( –

संबंधित मुद्दे