Android – Load a image in a file (not drawable) as image in the layout

Posted: February 9, 2012 in Android Dev
Sometimes, it is easier load a image from other directory (sdcard, for example) than load a image from drawable because for this last case, the image should be stored in the directory res/drawable first and packaged along with the apk files.

To load a image from a directory, it should be converted to the drawable first. Here comes a piece of code which can help:

File file = new File (“/sdcard/1.jpg”);
ImageView imageView = (ImageView) findViewById(R.id.icon);
imageView.setImageDrawable(Drawable.createFromPath(file.getAbsolutePath()));


Be warning that there is another method for ImageView called setImageURI(URI uri). This method is used to load external files, it doesn’t work with the type file. For example, this code won’t work:

File file = new File (“/sdcard/1.jpg”);
ImageView imageView = (ImageView) findViewById(R.id.icon);
imageView.setImageURI(Uri.fromFile(file));


Thanks Martin Wibbels for his post: http://mwibbels.blogspot.com/2010/11/imageviewsetimageuri-does-not-work-for.html

More information:
Android official Reference about ImageView: http://developer.android.com/reference/android/widget/ImageView.html
Android official Reference about Drawable:
http://developer.android.com/reference/android/graphics/drawable/Drawable.html

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s