Loading Images in Android (Part II: From Assets)

In this article we will look on how we can load images from the assets directory. If you are working in a gradle based project (eg. Android Studio), then you will find the assets directory at: src/main/assets, and in a standard Android project (eg. Eclipse + ADT), assets is located in the project's folder. By default the directory is empty.

In a previous article we examined how to load images from the drawable resource directory. You may ask what are the differences between the two and what benefits bring each of these 2 storage locations.

The benefits of drawable resources is that it provides built-in support for different OS versions, languages, screen orientation, etc. For example you can have normal images in the drawable-mdpi directory, and bigger ones in the drawable-xhdpi directory, then depending of the screen size, the system will pick the image from the appropriate directory. Also, as  shown in a previous article, the images stored in drawables can be referenced directly in the XML files.

None of the above mentioned benefits are available for assets. The assets directory can be used to store raw asset files. Files that you save here are compiled into an .apk file as-is, and the original filename is preserved. You can navigate this directory in the same way as a typical file system using URIs and read files as a stream of bytes using the AssetManager. For example, this is a good location for textures and game data.

To load an image from assets, we could use the getAssets().open(path) method of the Activity class. This will return an InputStream that passed to BitmapFactory.decodeStream(inputStream), will give us the image.
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_photo_loading);

    ImageView imageView = (ImageView) findViewById(R.id.image_view);

    try {
        InputStream inputStream = getAssets().open("image.png");
        Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
        imageView.setImageBitmap(bitmap);
    } catch (IOException e) {
        Log.d("TAG", "Could not load the image");
    }
}

Niciun comentariu:

Trimiteți un comentariu