I was trying to save images into the SQLite database, but even I compress and rescale my bitmap, the file was still too big, especially when you capture a image from the phone's camera.
Is there anyway to zip the bytearray/bitmap into a specific size like from 4mb to 500kb? If yes, how can I do that?
private void uriToFile(Uri uri, File sdImageMainDirectory) throws IOException {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
OutputStream stream = new FileOutputStream(sdImageMainDirectory);
int bitmapWidth = bitmap.getWidth();
int bitmapHeight = bitmap.getHeight();
int maxSize = 10;
float bitmapRatio = (float) bitmapWidth / (float) bitmapHeight;
if(bitmapRatio > 0){
bitmapWidth = maxSize;
bitmapHeight = (int) (bitmapWidth / bitmapRatio);
}
else{
bitmapHeight = maxSize;
bitmapWidth = (int) (bitmapHeight * bitmapRatio);
}
bitmap.createScaledBitmap(bitmap, bitmapWidth, bitmapHeight, true);
bitmap.compress(Bitmap.CompressFormat.JPEG, 30, stream);
stream.flush();
stream.close();
}
You're not actually compressing the scaled image, but rather, the original one. Change the last four lines to this:
Bitmap scaled = bitmap.createScaledBitmap(bitmap, bitmapWidth, bitmapHeight, true);
scaled.compress(Bitmap.CompressFormat.JPEG, 30, stream);
stream.flush();
stream.close();
createScaledBitmap()
returns the scaled bitmap, and you just lost the result.
You should be able to set maxSize
to 1000 and see file sizes below 500k.