Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Compress Bitmap from Uri

Tags:

android

Take a picture with the normal smartphone camera.

Ok I've been Googling this for a while now, and everyone seems to use something like the following:

Bitmap bm = BitmapFactory.decodeStream(getContentResolver().openInputStream(fileUri));
ByteArrayOutputStream out = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 25, out);
Bitmap decoded = BitmapFactory.decodeStream(new ByteArrayInputStream(out.toByteArray()));

I use this to check the file size:

@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
protected int sizeOf(Bitmap data) {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB_MR1) {
        return data.getRowBytes() * data.getHeight();
    } else {
        return data.getByteCount();
    }
}

The Bitmap is not getting any smaller, before and after:

Log.d("image", sizeOf(bm)+"");
Log.d("image", sizeOf(decoded)+"");

Results:

11-05 02:51:52.739: D/image(2558): 20155392
11-05 02:51:52.739: D/image(2558): 20155392

Pointers?

Answer:

BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 50;
Bitmap bmpSample = BitmapFactory.decodeFile(fileUri.getPath(), options);

Log.d("image", sizeOf(bmpPic)+"");

ByteArrayOutputStream out = new ByteArrayOutputStream();                
bmSample.compress(Bitmap.CompressFormat.JPEG, 1, out);
byte[] byteArray = out.toByteArray();

Log.d("image", byteArray.length/1024+"");
like image 544
basickarl Avatar asked Jan 25 '26 06:01

basickarl


1 Answers

The compress method, as mentioned in the documentation:

Write a compressed version of the bitmap to the specified outputstream. The bitmap can be reconstructed by passing a corresponding inputstream to BitmapFactory.decodeStream()

Thus the variable out now contains the compressed bitmap. Since you check the size after calling decodeStream the bitmap is decompressed and returned to you. Therefore the size is same.

like image 183
Amulya Khare Avatar answered Jan 26 '26 22:01

Amulya Khare