Here you can find the source of cropBitmapToSquare(Bitmap bitmap, int squareLength)
public static Bitmap cropBitmapToSquare(Bitmap bitmap, int squareLength)
import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Locale; import android.annotation.SuppressLint; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Matrix; import android.graphics.drawable.Drawable; import android.os.Build; import android.text.TextUtils; import android.widget.ImageView; public class Main{ /**/* w w w. j a v a 2 s .co m*/ * bitmap with alpha channel */ public static final String LOG_TAG = "BitmapUtils"; public static Bitmap cropBitmapToSquare(Bitmap bitmap, int squareLength) { if (bitmap != null) { int imageSquareLength = Math.min(bitmap.getWidth(), bitmap.getHeight()); int croppedLength = Math.min(imageSquareLength, squareLength); float scale = (float) croppedLength / imageSquareLength; Matrix matrix = new Matrix(); matrix.setScale(scale, scale); try { Bitmap newBitmap = Bitmap.createBitmap(bitmap, 0, 0, imageSquareLength, imageSquareLength, matrix, true); if (SDKVersionUtils.hasHoneycombMR1()) { newBitmap.setHasAlpha(bitmap.hasAlpha()); } return newBitmap; } catch (Throwable e) { e.printStackTrace(); } } return null; } public static Bitmap cropBitmapToSquare(String bitmapPath, int squareLength) { Bitmap bitmap = decodeSampledBitmapFromFile(bitmapPath, squareLength, squareLength); return cropBitmapToSquare(bitmap, squareLength); } public static Bitmap decodeSampledBitmapFromFile(String filePath, int reqWidth, int reqHeight) { if (TextUtils.isEmpty(filePath)) { return null; } final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; options.inPurgeable = true; options.inInputShareable = true; BitmapFactory.decodeFile(filePath, options); options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); options.inJustDecodeBounds = false; try { return BitmapFactory.decodeFile(filePath, options); } catch (Throwable e) { e.printStackTrace(); } return null; } public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { final int height = options.outHeight; final int width = options.outWidth; int inSampleSize = 1; if ((reqWidth > 0 && reqHeight > 0) && (height > reqHeight || width > reqWidth)) { if (width > height) { inSampleSize = Math.round((float) height / (float) reqHeight); } else { inSampleSize = Math.round((float) width / (float) reqWidth); } } return 0 == inSampleSize ? 1 : inSampleSize; } }