3

I have wrote this method before I noticed there is a compress method in Bitmap class.

/**
 * Calcuate how much to compress the image
 * @param options
 * @param reqWidth
 * @param reqHeight
 * @return
 */
public static int calculateInSampleSize(BitmapFactory.Options options,int reqWidth, int reqHeight) {

    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1; // default to not zoom image

    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;
    }
        return inSampleSize;
}

/**
 * resize image to 480x800
 * @param filePath
 * @return
 */
public static Bitmap getSmallBitmap(String filePath) {

    File file = new File(filePath);
    long originalSize = file.length();

    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(filePath, options);

    // Calculate inSampleSize based on a preset ratio
    options.inSampleSize = calculateInSampleSize(options, 480, 800);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;

    Bitmap compressedImage = BitmapFactory.decodeFile(filePath, options);


    return compressedImage;
}

I was wondering, compare to the built in Compress method, should I keep using this one, or switch to use the built in one? what is the difference?

Allan Jiang
  • 11,063
  • 27
  • 104
  • 165

2 Answers2

2

Basically

What you are doing in the above code is just resizing the image ,which will not loose much of the quality of the image since you use the SampleSize .

compress(Bitmap.CompressFormat format, int quality, OutputStream stream)

It is used when you want to change the imageFormat you have Bitmap.CompressFormat JPEG
Bitmap.CompressFormat PNG Bitmap.CompressFormat WEBP or to reduce the quality of the image using the quality parameter 0 - 100 .

Viswanath Lekshmanan
  • 9,945
  • 1
  • 40
  • 64
2

Your method is in line with Loading Large Bitmap guidelines

  • Large file on disk
  • Small bitmap in memory

compress() methods converts a large bitmap to a small one:

  • Large bitmap in memory
  • Small bitmap on disk (IOStream) (and possibly in different format)

I would use your method if I needed to load bitmap from a file to ImageViews of different sizes.

Y2i
  • 3,748
  • 2
  • 28
  • 32
  • Hmmm, actually I just did some test, and it looks like my code will not reduce the map – Allan Jiang Dec 15 '13 at 04:02
  • May be your bitmap is small enough already? Also, your calculateInSampleSize() is missing an iteration loop. Just copy&paste Google's code as a starting point. – Y2i Dec 15 '13 at 06:40