Reputation: 5795
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
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
Reputation: 663
Two options available
Upvotes: 0