ImageCompressUtil { 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 (height > reqHeight || width > reqWidth) { final int heightRatio = Math.round((float) height / (float) reqHeight); final int widthRatio = Math.round((float) width / (float) reqWidth); inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio; } float totalPixels = width * height; float totalReqPixelsCap = reqWidth * reqHeight * 2; while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) { inSampleSize++; } return inSampleSize; }  static byte[] convertImageToBytes(Bitmap imageSource); static Bitmap rotateBitmapByExif(String srcPath, Bitmap bitmap); static void recycleBitmap(Bitmap bitmap); static void storeImage(Bitmap image, String saveFilePath); static Bitmap compressImage(String filePath, float maxWidth, float maxHeight); static Bitmap compressByQuality(Bitmap bitmap, int maxSize); static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight); static Blob readImageFile(String filePath);  }
@Test public void should_return_sample_size_when_give_req_width_and_height() throws Exception { BitmapFactory.Options options = createBitmapFactoryOptions(4, 4); int actual = calculateInSampleSize(options, 2, 2); assertThat("should return 2 when ratio is 2", actual, is(2)); }
@Test public void should_return_sample_size_when_give_smaller_req_width_and_height() throws Exception { BitmapFactory.Options options = createBitmapFactoryOptions(4, 4); int actual = calculateInSampleSize(options, 3, 3); assertThat("Should return 1 when ratio is smaller than 2.", actual, is(1)); }
@Test public void should_return_sample_size_when_give_req_which_ratio_is_more_than_2_less_than_4() throws Exception { BitmapFactory.Options options = createBitmapFactoryOptions(9, 6); int actual = calculateInSampleSize(options, 3, 2); assertThat("Should return 3 when ratio is 3.", actual, is(3)); }
@Test public void should_return_sample_size_when_give_req_which_ratio_is_more_than_2() throws Exception { BitmapFactory.Options options = createBitmapFactoryOptions(8, 12); int actual = calculateInSampleSize(options, 2, 3); assertThat("Should return 4 when ratio is 4.", actual, is(4)); }