Loading images in Android (Part I: From Drawables and from Local Storage)

In these series of tutorials you will learn various ways of loading and displaying an image depending of image source. Specifically, we will look into:
  1. Loading an image from resource directory
  2. Loading an image from local storage
  3. Loading an image from assets directory
  4. Picking an image from Gallery
  5. Loading an image taken with Camera
  6. Loading an image from network
    1. Using AsyncTask
    2. Using Picasso image loading library
In Part I we will examine loading an image from resource and local storage.

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 method decodeFile(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