Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
96 views
in Technique[技术] by (71.8m points)

android - How to load a image from assets?

i need to load a image from assets to avoid a froyo 2.2.2 bug resizing POT images in some particular cases. The way to avoid it is loading the image files from assets dir.

I'm trying to do with this:

String imagePath = "radiocd5.png";
AssetManager mngr = context.getAssets();
// Create an input stream to read from the asset folder
InputStream is = null;
try {
    is = mngr.open(imagePath);
} catch (IOException e1) { e1.printStackTrace();}
    
//Get the texture from the Android resource directory
//InputStream is = context.getResources().openRawResource(R.drawable.radiocd5);
Bitmap bitmap = null;
try {
    //BitmapFactory is an Android graphics utility for images
    bitmap = BitmapFactory.decodeStream(is);

} finally {
    //Always clear and close
    try {
        is.close();
        is = null;
    } catch (IOException e) {}
}

But i am getting NullPointerException on the line is.close();

i capture a FileNotFoundException: radiocd5.png, but that file is on my assets directory :S

What am i doing bad? The file is called radiocd5.png and it is on the assets directory

question from:https://stackoverflow.com/questions/7645268/how-to-load-a-image-from-assets

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can follow my tutorials on displaying data from Assets: https://xjaphx.wordpress.com/2011/10/02/store-and-use-files-in-assets/
The sample with loading image and text to display.

I now added the relevant part of the provided link (in case of earthquake or something) ;-) Taifun

// load image
try {
    // get input stream
    InputStream ims = getAssets().open("avatar.jpg");
    // load image as Drawable
    Drawable d = Drawable.createFromStream(ims, null);
    // set image to ImageView
    mImage.setImageDrawable(d);
}
catch(IOException ex) {
    return;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...