Android How to - Load Image and Text from Asset








Question

We would like to know how to load Image and Text from Asset.

Answer

//from   w  w  w. j a  v a2  s.  c om
/**********************************************************************
 * Copyright (c) 2015 Luka Kunic, "ActivityUtils.java"
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * 
 * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed
 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for
 * the specific language governing permissions and limitations under the License.
 *
 * Author: lkunic
 * Last modified: 08/02/2015
 **********************************************************************/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

class ActivityUtils {
  private static final int THUMBNAIL_SIZE = 1024;

  /**
   * Loads given image asset, scaling the image down if it is too big to improve
   * performance.
   * 
   * @param context
   *          Application context
   * @param path
   *          Path in the assets folder of the image to load
   * @return Loaded image bitmap
   */
  public static Bitmap loadImageFromAssets(Context context, String path) {
    try {
      // Open the input stream to the image in assets
      InputStream is = context.getAssets().open(path);

      // Load the image dimensions first so that big images can be scaled down
      // (improves memory usage)
      BitmapFactory.Options onlyBoundsOptions = new BitmapFactory.Options();
      onlyBoundsOptions.inJustDecodeBounds = true;
      onlyBoundsOptions.inDither = true;
      BitmapFactory.decodeStream(is, null, onlyBoundsOptions);
      is.close();

      if ((onlyBoundsOptions.outWidth == -1)
          || (onlyBoundsOptions.outHeight == -1)) {
        // There was an error while decoding
        return null;
      }

      // Find the bigger dimension (width, height)
      int originalSize = (onlyBoundsOptions.outHeight > onlyBoundsOptions.outWidth) ? onlyBoundsOptions.outHeight
          : onlyBoundsOptions.outWidth;

      // Calculate the sampling ratio for images that are bigger than the
      // thumbnail size
      double ratio = (originalSize > THUMBNAIL_SIZE) ? (originalSize / THUMBNAIL_SIZE)
          : 1.0;
      int sampleSize = Integer.highestOneBit((int) Math.floor(ratio));

      // Load the image sampled using the calculated ratio
      BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
      bitmapOptions.inSampleSize = sampleSize;
      bitmapOptions.inDither = true;
      is = context.getAssets().open(path);
      Bitmap bitmap = BitmapFactory.decodeStream(is, null, bitmapOptions);
      is.close();

      return bitmap;
    } catch (IOException e) {
      return null;
    }
  }

  /**
   * Loads lines of text from the given path in the assets directory.
   * 
   * @param context
   *          Application context.
   * @param path
   *          Path in the assets folder to the text file to load.
   * @return String array representing lines of text in the file.
   */
  public static String[] loadTextFromAssets(Context context, String path) {
    try {
      // Open the input stream to the text in assets
      InputStream inputStream = context.getAssets().open(path);
      InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
      BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

      List<String> lines = new ArrayList<String>();

      String line;
      while ((line = bufferedReader.readLine()) != null) {
        lines.add(line);
      }

      inputStream.close();

      return lines.toArray(new String[lines.size()]);
    } catch (IOException e) {
      return null;
    }
  }
}