Android examples for Graphics:Bitmap Crop
read Image Center Crop
//package com.java2s; import android.content.Context; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Matrix; import android.net.Uri; import android.provider.MediaStore; import java.io.IOException; import java.io.InputStream; public class Main { public static Bitmap readImageCenterCrop(Context context, Uri selectedImage) {//from ww w . ja va2s .c om Bitmap srcBmp = null; try { srcBmp = getCorrectlyOrientedImage(context, selectedImage); } catch (IOException e) { e.printStackTrace(); } Bitmap dstBmp; if (srcBmp.getWidth() >= srcBmp.getHeight()) { dstBmp = Bitmap.createBitmap(srcBmp, srcBmp.getWidth() / 2 - srcBmp.getHeight() / 2, 0, srcBmp.getHeight(), srcBmp.getHeight()); } else { dstBmp = Bitmap.createBitmap(srcBmp, 0, srcBmp.getHeight() / 2 - srcBmp.getWidth() / 2, srcBmp.getWidth(), srcBmp.getWidth()); } return dstBmp; } public static Bitmap getCorrectlyOrientedImage(Context context, Uri photoUri) throws IOException { int MAX_IMAGE_DIMENSION = 512; InputStream is = context.getContentResolver().openInputStream( photoUri); BitmapFactory.Options dbo = new BitmapFactory.Options(); dbo.inJustDecodeBounds = true; BitmapFactory.decodeStream(is, null, dbo); is.close(); int rotatedWidth, rotatedHeight; int orientation = getOrientation(context, photoUri); if (orientation == 90 || orientation == 270) { rotatedWidth = dbo.outHeight; rotatedHeight = dbo.outWidth; } else { rotatedWidth = dbo.outWidth; rotatedHeight = dbo.outHeight; } Bitmap srcBitmap; is = context.getContentResolver().openInputStream(photoUri); if (rotatedWidth > MAX_IMAGE_DIMENSION || rotatedHeight > MAX_IMAGE_DIMENSION) { float widthRatio = ((float) rotatedWidth) / ((float) MAX_IMAGE_DIMENSION); float heightRatio = ((float) rotatedHeight) / ((float) MAX_IMAGE_DIMENSION); float maxRatio = Math.max(widthRatio, heightRatio); // Create the bitmap from file BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = (int) maxRatio; srcBitmap = BitmapFactory.decodeStream(is, null, options); } else { srcBitmap = BitmapFactory.decodeStream(is); } is.close(); /* * if the orientation is not 0 (or -1, which means we don't know), we * have to do a rotation. */ if (orientation > 0) { Matrix matrix = new Matrix(); matrix.postRotate(orientation); srcBitmap = Bitmap.createBitmap(srcBitmap, 0, 0, srcBitmap.getWidth(), srcBitmap.getHeight(), matrix, true); } return srcBitmap; } private static int getOrientation(Context context, Uri photoUri) { /* it's on the external media. */ Cursor cursor = context .getContentResolver() .query(photoUri, new String[] { MediaStore.Images.ImageColumns.ORIENTATION }, null, null, null); if (cursor.getCount() != 1) { return -1; } cursor.moveToFirst(); return cursor.getInt(0); } }