Darpan
Darpan

Reputation: 5795

Convert a bitmap to a fixed size

For example, I have a 10mb image; which I want to convert to 300kb. I have been through many examples used

bmp.compress(Bitmap.CompressFormat.JPEG, 100, stream);

(here changing 100 to a lesser value will decrease the size but how would it result in a size close to 300-350kb)

and

BitmapFactory.decodeFile(filePath, options);

where I provided

options.inSampleSize = 5 /*sample*/;

But somehow I am missing something.

UPDATE Settled with conversion 11mb to 2mb. Will update if I find a better way.

Upvotes: 1

Views: 342

Answers (2)

weston
weston

Reputation: 54811

I think because PNG is lossless, the quality parameter has no effect. It's not going to "crunch" your PNGs. However this approach would work for jpg:

Trial and error, with a binary search will get you close very quickly, 3-4 attempts probably depending on the size of the acceptable range.

int minQuality = 10;
int maxQuality = 100;
long size = 0;
while(true) {
  int mid = (maxQuality + minQuality)/2;        
  long size = compress(mid);

  if (size > minSize) { //too large
     if (maxQuality == minQuality){
       throw new RuntimeException("Cannot compress this image down in to this size range.");
     }
     maxQuality = mid - 1;
     continue;
  }

  if (size < maxSize) { //too small
     if(maxQuality == 100){
       break; //this means the image is smaller than the acceptable range even at 100
     }
     minQuality = mid + 1;
     continue;
  }

  break;//done, falls in range 
}

Upvotes: 2

krishnakumar sekar
krishnakumar sekar

Reputation: 663

Two options available

  1. Decrease the contrast of the image using image processing or some image processing api for android or do sampling using image processing api
  2. Repeat the bmp.compress(Bitmap.CompressFormat.PNG, 100, stream); for several times by storing the image outside and again reading in each time

Upvotes: 0

Related Questions