Monday, 8 August 2011

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

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


No comments:

Post a Comment