Android開発記録雑記 -6ページ目

Android開発記録雑記

パソコン中級者ぐらいの私が
スマホアプリの開発をしてみようと思い立ち
Androidで動くアプリ開発過程をこれから書き記していきます。

今回から新たな項目 Loading Large Bitmaps Efficiently
です。

ビットマップ画像を効率よく開く方法についてです。

というのも、まだまだスマホのメモリ容量には制限が多く
デカイ画像を開くとそれだけでメモリ不足になります。

具体的には、
単一のアプリケーションが使用できるメモリは16メガバイト
Androidの互換性の定義文書 セクション3.7より

なので、
2592x1936ピクセル(500万画素)に写真をとる。と
2592 * 1936 * 4バイトのメモリを約19メガバイト
となりこの制約をオーバーしてしまいます。


したがって、大きいビットマップはデコードします。


まず、ビットマップの寸法を取得します。
BitmapFactory.Options options = new BitmapFactory.Options();
ビットマップのメモリ割り当てを回避する
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(getResources(), R.id.myimage, options);
元のサイズの大きさを取得する
int imageHeight = options.outHeight;
int imageWidth = options.outWidth;
String imageType = options.outMimeType;



これを元にビットマップの縮小比を計算

public static int calculateInSampleSize(
            BitmapFactory.Options options, int reqWidth, int reqHeight) {
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {
要求する大きさの倍数を得る
        final int heightRatio = Math.round((float) height / (float) reqHeight);
        final int widthRatio = Math.round((float) width / (float) reqWidth);

        inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
    }

    return inSampleSize;
}

inSampleSize = 4 の場合
解像度2048x1536のビットマップは約512x384のビットマップを生成します
メモリは12MBから0.75MBに圧縮されます。

これを使ってビットマップをロードする
public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
        int reqWidth, int reqHeight) {
    final BitmapFactory.Options options = new BitmapFactory.Options();

    options.inJustDecodeBounds = true;
    BitmapFactory.decodeResource(res, resId, options);

    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeResource(res, resId, options);
}


100x100のサムネイル表示はこんな感じ
mImageView.setImageBitmap(
decodeSampledBitmapFromResource(getResources()、R.id.myimage、100、100));


本日は以上です。