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.content.Context;

import android.graphics.*;

import android.net.Uri;

import java.io.InputStream;

public class Main {
    public static final Bitmap getBitmapFromUri(Context context, Uri uri) {
        if (uri == null)
            return null;
        try {
            InputStream is = context.getContentResolver().openInputStream(uri);
            BitmapFactory.Options imageOptions = new BitmapFactory.Options();
            Bitmap bmp = BitmapFactory.decodeStream(is, null, imageOptions);
            return bmp;
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    public static final Bitmap getBitmapFromUri(Context context, Uri uri, int maxWidth, int maxHeight) {
        if (uri == null)
            return null;
        try {
            InputStream is = context.getContentResolver().openInputStream(uri);

            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            // Set height and width in options, does not return an image and no resource taken
            BitmapFactory.decodeStream(is, null, options);
            int pow = 0;
            while (options.outHeight >> pow > maxHeight || options.outWidth >> pow > maxWidth) {
                pow += 1;
            }
            is.close();
            is = context.getContentResolver().openInputStream(uri);
            options.inSampleSize = 1 << pow;
            options.inJustDecodeBounds = false;
            Bitmap bmp = BitmapFactory.decodeStream(is, null, options);

            return bmp;
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }
}