Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Apache License 

import android.app.Activity;

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

import android.net.Uri;

import java.io.File;

import java.io.IOException;
import java.io.InputStream;

public class Main {
    /**
     * Get Bitmap from Uri
     *
     * @param uri Uri to get Bitmap
     * @return
     * @throws FileNotFoundException
     * @throws IOException
     */
    public static Bitmap getImageFromUri(Activity activity, Uri uri, File file) throws IOException {

        BitmapFactory.Options onlyBoundsOptions = new BitmapFactory.Options();
        onlyBoundsOptions.inJustDecodeBounds = true;
        onlyBoundsOptions.inDither = true;//optional
        onlyBoundsOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;//optional
        if (file != null) {
            BitmapFactory.decodeFile(file.getAbsolutePath(), onlyBoundsOptions);
        } else {
            InputStream input = activity.getContentResolver().openInputStream(uri);
            BitmapFactory.decodeStream(input, null, onlyBoundsOptions);
            input.close();
        }

        if ((onlyBoundsOptions.outWidth == -1) || (onlyBoundsOptions.outHeight == -1))
            return null;

        float scale = activity.getResources().getDisplayMetrics().density;
        int pHeight = (int) (activity.getResources().getConfiguration().screenHeightDp * scale + 0.5f);
        int originalSize = (onlyBoundsOptions.outHeight > onlyBoundsOptions.outWidth) ? onlyBoundsOptions.outHeight
                : onlyBoundsOptions.outWidth;

        double ratio = (originalSize > pHeight) ? (originalSize / pHeight) : 1.0;

        int REQUIRED_SIZE = activity.getResources().getDisplayMetrics().heightPixels / 2;

        /**/
        int Scale = 1;
        while (onlyBoundsOptions.outWidth / Scale / 2 >= REQUIRED_SIZE
                && onlyBoundsOptions.outHeight / Scale / 2 >= REQUIRED_SIZE) {
            Scale *= 2;
        }
        /**/

        BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
        bitmapOptions.inSampleSize = Scale;//getPowerOfTwoForSampleRatio(ratio);
        bitmapOptions.inDither = true;//optional
        bitmapOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;//optional

        Bitmap bitmap;
        if (file != null) {
            bitmap = BitmapFactory.decodeFile(file.getAbsolutePath(), bitmapOptions);
        } else {
            InputStream input = activity.getContentResolver().openInputStream(uri);
            bitmap = BitmapFactory.decodeStream(input, null, bitmapOptions);
            input.close();
        }

        return bitmap;
    }
}