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.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

import java.io.IOException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import android.graphics.Matrix;

import android.media.ExifInterface;

public class Main {
    public static Bitmap decodeFileAndResize(File f, int requiredSize) {
        try {

            int rotation = 0;
            try {
                ExifInterface exif = new ExifInterface(f.getAbsolutePath());
                int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
                rotation = getRotation(orientation);
            } catch (IOException e) {
                e.printStackTrace();
            }
            // decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(new FileInputStream(f), null, o);

            // Find the correct scale value. It should be the power of 2.
            final int REQUIRED_SIZE = requiredSize;
            int width_tmp = o.outWidth, height_tmp = o.outHeight;
            int scale = 1;
            while (true) {
                if (width_tmp / 2 < REQUIRED_SIZE || height_tmp / 2 < REQUIRED_SIZE) {
                    break;
                }
                width_tmp /= 2;
                height_tmp /= 2;
                scale *= 2;
            }
            // decode with inSampleSize
            return createScaledBitmap(f, rotation, scale);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static int getRotation(int orientation) {
        switch (orientation) {
        case ExifInterface.ORIENTATION_ROTATE_270:
            return 270;

        case ExifInterface.ORIENTATION_ROTATE_90:
            return 90;

        default:
            return 0;
        }
    }

    private static Bitmap createScaledBitmap(File f, int rotation, int scale) throws FileNotFoundException {
        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize = scale;
        Bitmap bitmap = BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
        if (0 < rotation) {
            Matrix matrix = new Matrix();
            matrix.postRotate(rotation);
            Bitmap rotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix,
                    true);
            if (rotatedBitmap != bitmap) {
                bitmap.recycle();
                bitmap = null;
            }
            return rotatedBitmap;
        }
        return bitmap;
    }
}