Java tutorial
//package com.java2s; //License from project: Apache License import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Matrix; import android.media.ExifInterface; import java.io.ByteArrayOutputStream; import java.io.IOException; public class Main { public static Bitmap decodeSampledBitmapFromFd(String pathName, int reqWidth, int reqHeight) { final BitmapFactory.Options options = new BitmapFactory.Options(); // options.inJustDecodeBounds = true; // BitmapFactory.decodeFile(pathName, options); int sampleSize = calculateInSampleSize(options, reqWidth, reqHeight); // if(sampleSize < 4) // { // sampleSize = 4; // } options.inSampleSize = sampleSize; options.inJustDecodeBounds = false; Bitmap src = BitmapFactory.decodeFile(pathName, options); return src; } public static Bitmap decodeSampledBitmapFromFd(String filePath) { final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(filePath, options); // Calculate inSampleSize // if(Build.VERSION.SDK_INT < 19) // { // options.inSampleSize = calculateInSampleSize(options, 300, 300); // } // else // { options.inSampleSize = calculateInSampleSize(options, 480, 480); // } // Decode bitmap with inSampleSize set options.inJustDecodeBounds = false; Bitmap bm = BitmapFactory.decodeFile(filePath, options); if (bm == null) { return null; } int degree = readPictureDegree(filePath); bm = rotateBitmap(bm, degree); ByteArrayOutputStream baos = null; try { baos = new ByteArrayOutputStream(); bm.compress(Bitmap.CompressFormat.JPEG, 30, baos); } finally { try { if (baos != null) baos.close(); } catch (IOException e) { e.printStackTrace(); } } return bm; } private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { final int height = options.outHeight; final int width = options.outWidth; int inSampleSize = 1; if (height > reqHeight || width > reqWidth) { final int halfHeight = height / 2; final int halfWidth = width / 2; while ((halfHeight / inSampleSize) > reqHeight && (halfWidth / inSampleSize) > reqWidth) { inSampleSize *= 2; } } return inSampleSize; } private static int readPictureDegree(String path) { int degree = 0; try { ExifInterface exifInterface = new ExifInterface(path); int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL); switch (orientation) { case ExifInterface.ORIENTATION_ROTATE_90: degree = 90; break; case ExifInterface.ORIENTATION_ROTATE_180: degree = 180; break; case ExifInterface.ORIENTATION_ROTATE_270: degree = 270; break; } } catch (IOException e) { e.printStackTrace(); } return degree; } private static Bitmap rotateBitmap(Bitmap bitmap, int rotate) { if (bitmap == null) return null; int w = bitmap.getWidth(); int h = bitmap.getHeight(); // Setting post rotate to 90 Matrix mtx = new Matrix(); mtx.postRotate(rotate); return Bitmap.createBitmap(bitmap, 0, 0, w, h, mtx, true); } }