- Loading an image from resource directory
- Loading an image from local storage
- Loading an image from assets directory
- Picking an image from Gallery
- Loading an image taken with Camera
- Loading an image from network
- Using AsyncTask
- Using Picasso image loading library
Loading an image from drawable resource directory.
Loading an image from drawable directory is one of the simplest and common use cases. You use this when you have static images bundled within your application.Assuming an image is located at:
res/drawable/image.png
, you can load it using the following methods:a) directly in the XML file:
<ImageView android:id="@+id/image_view" android:layout_height="wrap_content" android:layout_width="wrap_content" android:src="@drawable/image" />The
src
attribute is taking the resource type: @drawable/
and the resource id: image
(which is the file name without extention).b) programmatically:
// Get a reference to the ImageView ImageView imageView = (ImageView)findViewById(R.id.image_view); // Set the image imageView.setImageResource(R.drawable.image);The programmatic method is useful in scenarios where the image to be displayed is to be decided at runtime, for example in response to a particular user action.
Loading an image from local storage.
Assuming that an image is located in the phone's external storage, in a directory called Pictures, it can be loaded using the static methoddecodeFile(path)
of the class BitmapFactory
.ImageView imageView = (ImageView) findViewById(R.id.image_view); Bitmap bitmap = BitmapFactory.decodeFile( Environment.getExternalStorageDirectory() + "/Pictures/image.png"); if (bitmap != null) { imageView.setImageBitmap(bitmap); } else { Toast.makeText(this, "Can't load image", Toast.LENGTH_SHORT).show(); }
Note that if you will try to load large images, you may run into the famous
OutOfMemoryError
. Normally, displaying an image involves some preprocessing, like scaling down the image before loading it in memory, and this is the subject of the next article.
Niciun comentariu:
Trimiteți un comentariu