decode File to Bitmap - Android Graphics

Android examples for Graphics:Bitmap File

Description

decode File to Bitmap

Demo Code


import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import java.io.BufferedInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

public class Main{
    public static Bitmap decodeFile(final String filename,
            final int maxSize, final boolean square) throws IOException {
        final int angle = ExifUtils.getAngle(filename);

        final BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inJustDecodeBounds = true;//from w  w w  .j  a v  a  2 s .  c o m
        BitmapFactory.decodeFile(filename, opts);

        final int size = Math.max(opts.outWidth, opts.outHeight);
        if (size > maxSize) {
            opts.inSampleSize = size / maxSize;
        } else {
            opts.inSampleSize = 1;
        }

        Bitmap bitmap = decodeFile(filename, opts.inSampleSize, 0, 2);
        if (angle != 0) {
            final Matrix matrix = new Matrix();
            matrix.postRotate(angle);
            final Bitmap _bitmap = Bitmap.createBitmap(bitmap, 0, 0,
                    bitmap.getWidth(), bitmap.getHeight(), matrix, false);
            bitmap.recycle();
            bitmap = _bitmap;
        }
        if (square && bitmap.getWidth() != bitmap.getHeight()) {
            if (bitmap.getWidth() > bitmap.getHeight()) {
                final Bitmap _bitmap = Bitmap.createBitmap(bitmap,
                        (bitmap.getWidth() - bitmap.getHeight()) / 2, 0,
                        bitmap.getHeight(), bitmap.getHeight());
                bitmap.recycle();
                bitmap = _bitmap;
            } else if (bitmap.getWidth() < bitmap.getHeight()) {
                final Bitmap _bitmap = Bitmap.createBitmap(bitmap, 0,
                        (bitmap.getHeight() - bitmap.getWidth()) / 2,
                        bitmap.getWidth(), bitmap.getWidth());
                bitmap.recycle();
                bitmap = _bitmap;
            }
        }
        return bitmap;
    }
    public static Bitmap decodeFile(final String pathName) {
        return decodeFile(pathName, 1, 0, 2);
    }
    public static Bitmap decodeFile(final String pathName,
            final int startInSampleSize, final int add, final int multi) {
        final BitmapFactory.Options opts = new BitmapFactory.Options();
        int inSampleSize = startInSampleSize;
        while (true) {
            opts.inSampleSize = inSampleSize;
            opts.inDither = true;
            try {
                return BitmapFactory.decodeFile(pathName, opts);
            } catch (final OutOfMemoryError e) {
                inSampleSize = (inSampleSize + add) * multi;
            }
        }
    }
}

Related Tutorials