Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import android.app.Activity;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class Main {

    public static Bitmap readBitmapFromPath(Activity context, String filePath) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);
        int outWidth = options.outWidth;
        int outHeight = options.outHeight;
        options.inJustDecodeBounds = false;
        int be = calculateInSampleSize(context, outWidth, outHeight);
        options.inSampleSize = be;
        options.inPurgeable = true;
        options.inInputShareable = true;
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        try {
            return BitmapFactory.decodeFile(filePath, options);
        } catch (OutOfMemoryError e) {
            System.gc();
            try {
                options.inSampleSize = be + 1;
                return BitmapFactory.decodeFile(filePath, options);

            } catch (OutOfMemoryError e2) {
                return null;
            }
        }
    }

    public static int calculateInSampleSize(Activity context, int outWidth, int outHeight) {
        int screenWidth = context.getWindowManager().getDefaultDisplay().getWidth();
        int screenHeight = context.getWindowManager().getDefaultDisplay().getHeight();
        int be;
        if (outWidth > screenWidth || outHeight > 1.5 * screenHeight) {
            int heightRatio = Math.round(((float) outHeight) / ((float) 1.5 * screenHeight));
            int widthRatio = Math.round(((float) outWidth) / ((float) screenWidth));
            int sample = heightRatio > widthRatio ? heightRatio : widthRatio;
            if (sample < 3)
                be = sample;
            else if (sample < 6.5)
                be = 4;
            else if (sample < 8)
                be = 8;
            else
                be = sample;
        } else {
            be = 1;
        }
        if (be <= 0) {
            be = 1;
        }
        return be;
    }
}