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.Bitmap;

import android.graphics.BitmapFactory;

import android.net.Uri;

import java.io.ByteArrayOutputStream;

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

public class Main {
    private static final int MAX_WIDTH = 480;
    private static final int MAX_HEIGHT = 800;

    public static Bitmap getImageFromUri(Context ctx, Uri uri, int reqWidth, int reqHeight) throws IOException {
        InputStream iStream = ctx.getContentResolver().openInputStream(uri);
        byte[] inputData = getBytes(iStream);

        return decodeSampledBitmapFromBytes(inputData, reqWidth, reqHeight);
    }

    public static byte[] getBytes(InputStream inputStream) throws IOException {
        ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
        int bufferSize = 1024;
        byte[] buffer = new byte[bufferSize];

        int len = 0;
        while ((len = inputStream.read(buffer)) != -1) {
            byteBuffer.write(buffer, 0, len);
        }

        return byteBuffer.toByteArray();
    }

    public static Bitmap decodeSampledBitmapFromBytes(byte[] res, int reqWidth, int reqHeight) {
        if (reqWidth > MAX_WIDTH)
            reqWidth = MAX_WIDTH;
        if (reqHeight > MAX_HEIGHT)
            reqHeight = MAX_HEIGHT;

        // First decode with inJustDecodeBounds=true to check dimensions
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        options.inPurgeable = true;
        options.inInputShareable = true;
        BitmapFactory.decodeByteArray(res, 0, res.length, options);

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

        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;

        return BitmapFactory.decodeByteArray(res, 0, res.length, options);
    }

    private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        // Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {
            if (width > height)
                inSampleSize = Math.round((float) height / (float) reqHeight);
            else
                inSampleSize = Math.round((float) width / (float) reqWidth);
        }

        return inSampleSize;
    }
}