Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Open Source License 

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import android.content.Context;

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

import android.net.Uri;

import android.util.Log;

public class Main {
    private static final int MAX_IMAGE_DIMENSION = 972;

    private static Bitmap readScaledBitmapFromUri(Uri photoUri, Context context, int width, int height)
            throws FileNotFoundException, IOException {
        Log.i("Photo Editor", "Read Scaled Bitmap: " + width + " " + height);
        InputStream is;
        Bitmap srcBitmap;
        is = context.getContentResolver().openInputStream(photoUri);
        if (width > MAX_IMAGE_DIMENSION || height > MAX_IMAGE_DIMENSION) {
            float ratio = calculateScaleRatio(width, height);
            Log.i("Photo Editor", "Scaled Bitmap: " + ratio);
            srcBitmap = readRoughScaledBitmap(is, ratio);
            ratio = calculateScaleRatio(srcBitmap.getWidth(), srcBitmap.getHeight());
            srcBitmap = scaleBitmap(srcBitmap, ratio);
        } else {
            Log.i("Photo Editor", "NOT Scaled Bitmap ");
            srcBitmap = BitmapFactory.decodeStream(is);
        }
        is.close();
        return srcBitmap;
    }

    private static float calculateScaleRatio(int width, int height) {
        float widthRatio = ((float) width) / ((float) MAX_IMAGE_DIMENSION);
        float heightRatio = ((float) height) / ((float) MAX_IMAGE_DIMENSION);
        float maxRatio = Math.max(widthRatio, heightRatio);
        return maxRatio;
    }

    private static Bitmap readRoughScaledBitmap(InputStream is, float maxRatio) {
        Bitmap result;
        // Create the bitmap from file
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = (int) maxRatio;
        result = BitmapFactory.decodeStream(is, null, options);
        if (result != null) {
            Log.i("Photo Editor", "Read Scaled Bitmap Result wtf: " + result.getWidth() + " " + result.getHeight());
            Log.i("Photo Editor", "MaxRatio wtf: " + maxRatio);
        }
        return result;
    }

    private static Bitmap scaleBitmap(Bitmap bitmap, float ratio) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();

        Matrix matrix = new Matrix();
        matrix.postScale(1f / ratio, 1f / ratio);

        Bitmap result = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
        return result;
    }
}